我最近使用过WebGrude用于从网页上抓取一些内容。然后我尝试从 e-bay 上抓取一些搜索结果。这里尝试过,
@Page("http://www.ebay.com/sch/{0}")
public class PirateBay {
public static void main(String[] args) {
//Search calls Browser, which loads the page on a PirateBay instance
PirateBay search = PirateBay.search("iPhone");
while (search != null) {
search.magnets.forEach(System.out::println);
search = search.nextPage();
}
}
public static PirateBay search(String term) {
return Browser.get(PirateBay.class, term);
}
private PirateBay() {
}
/*
* This selector matches all magnet links. The result is added to this String list.
* The default behaviour is to use the rendered html inside the matched tag, but here
* we want to use the href value instead.
*/
@Selector(value = "#ResultSetItems a[href*=magnet]", attr = "href")
public List<String> magnets;
/*
* This selector matches a link to the next page result, wich can be mapped to a PirateBay instance.
* The Link next gets the page on the href attribute of the link when method visit is called.
*/
@Selector("a:has(img[alt=Next])")
private Link<PirateBay> next;
public PirateBay nextPage() {
if (next == null)
return null;
return next.visit();
}
}
但是结果是空的。我如何使用它来抓取搜索结果?
选择器“#ResultSetItems a[href*=magnet]”选择 href 属性值包含字符串“magnet”的链接。
在这里您可以阅读有关属性选择器的更多信息:attribute_selectors
您想要的是“#ResultSetItems h3.lvtitle a”
为了测试你的选择器,有一个很好的 repl,它使用 Jsoup,与 webgrude Try jsoup 使用的库相同。
我是一名优秀的程序员,十分优秀!