我正在尝试使用JSoup从一个网站上抓取一些内容。下面是我感兴趣的页面中的一些HTML内容示例:
<div class="sep_top shd_hdr pb2 luna">
<div class="KonaBody" style="padding-left:0px;">
<div class="lunatext results_content frstluna">
<div class="luna-Ent">
<div class="header">
<div class="body">
<div class="pbk">
<div id="rltqns">
<div class="pbk">
<span class="pg">
<span id="hotword">
<span id="hotword">Fizz</span>
</span>
</span>
<div class="luna-Ent">
<div class="luna-Ent">
<div class="luna-Ent">
<div class="luna-Ent">
</div>
<div class="pbk">
<span class="sectionLabel">
<span class="pg">
<span id="hotword">
<span id="hotword">Buzz</span>
</span>
</span>
<span class="pg">
<span id="hotword">
<span id="hotword">Foo</span>
</span>
</span>
<span class="pg">
<span id="hotword">
<span id="hotword">Bar</span>
</span>
</span>
</div>
<div class="tail">
</div>
<div class="rcr">
<!-- ... rest of content omitted for brevity -->我有兴趣获得页面中所有hotwords的列表(所以"Fizz“、"Buzz”、"Foo“和"Bar")。但是,我不能只查询hotword**,,因为它们在各处都使用** hotword 类来装饰许多不同的元素。特别是,需要存在于pbk pg hotword元素中的所有hotwords。请注意,pbks可以包含0+命令,pgs可以包含0+热词,热词可以包含1+其他热词。我有以下代码:
// Update, per PShemo:
Document doc = Jsoup.connect("http://somesite.example.com").get();
System.out.println("Starting to crawl...");
// Get the document's .pbk elements.
Elements pbks = doc.select(".pbk");
List<String> hotwords = new ArrayList<String>();
System.out.println(String.format("Found %s pbks.", pbks.size()));
int pbkCount = 0;
for(Element pbk : pbks) {
pbkCount++;
// Get the .pbk element's .pg elements.
for(Element pg : pbk.getElementsByClass("pg")) {
System.out.println(String.format("PBK #%s has %s pgs.", pbkCount, pbk.getElementsByClass("pg").size()));
Element hotword = pg.getElementById("hotword");
System.out.println("Adding hotword: " + hotword.text());
hotwords.add(hotword.text());
}
}运行该代码将产生以下输出:
Starting to crawl...
Found 3 pbks.我要么没有正确使用JSoup API,要么没有使用正确的选择器,或者两者兼而有之。对我要去哪里有什么想法吗?
发布于 2013-11-12 20:35:37
如果您使用的是getElementsByClass,那么您不需要在它之前添加.,只需使用类名,比如getElementsByClass("pg"),而不是getElementsByClass(".pg")
getElementById也是如此。不要在#值之前添加id。只需使用getElementById("hotword")。
而且,您的带有div类的pbk类似乎是嵌套的,因此getElementsByClass可以给出重复的结果。
在知道您要解析的页面之后,您可以使用一个选择器完成它。试试这条路
for (Element element:doc.select("div.body div.pbk span.pg")){
System.out.println(element.text());
}发布于 2013-11-12 20:32:49
Elements hotwords = document.select("#hotwords");
for (Element hotword : hotwords){
String word = hotword.getText();
}https://stackoverflow.com/questions/19939129
复制相似问题