我正在解析一个网页,我可以解析 id 但不能解析类。这就是我的意思;我正在解析整个新闻包装器 ID:
protected String getBlogStats() throws Exception {
String result = "";
// get html document structure
Document document = Jsoup.connect(BLOG_URL).get();
// selector query
Elements nodeBlogStats = document.select("div#news_wrapper");
// check results
if(nodeBlogStats.size() > 0) {
// get value
result = nodeBlogStats.get(0).text();
}
// return
return result;
}
它有效,我可以显示所有内容,但我只需要选择此包装器内的 h3 标签,所以我尝试了这种方式:
protected String getBlogStats() throws Exception {
String result = "";
// get html document structure
Document document = Jsoup.connect(BLOG_URL).get();
// selector query
Elements nodeBlogStats = document.select("div#news_wrapper .news-col-1 h3");
// check results
if(nodeBlogStats.size() > 0) {
// get value
result = nodeBlogStats.get(0).text();
}
// return
return result;
}
news-col-1
是一个类..但 Activity 是空白的..是否有另一种方法来编写用 jsoup 解析的类?谢谢
最佳答案
使用类获取该 div 内所有 h3 标签的一种可能方法是:
Elements nodeBlogStats = doc.select("div.news-col-0 h3");
它不适用于 .news-col-1
因为没有<h3>
标签是该 div 的直接子元素。正如您评论的那样,该 id 也将起作用:
Elements nodeBlogStats = doc.select("div#news_wrapper h3");
您的代码仅返回第一个 h3 而不是全部的原因是因为您将结果设置为仅 nodeBlogStats
中第一个元素的文本。 (当你说 get(0)
时):
if(nodeBlogStats.size() > 0) {
// get value
result = nodeBlogStats.get(0).text();
}
考虑返回 List
或 nodeBlogStats.text()
如果你想要所有的 h3 文本。
更新:
因此您可以更改方法以返回 ArrayList
.
protected ArrayList<String> getBlogStats() throws Exception {
// get html document structure
Document document = Jsoup.connect(BLOG_URL).get();
// selector query
Elements nodeBlogStats = document.select("div#news_wrapper");
// check results
ArrayList<String> list = new ArrayList<String>();
for (Element e : nodeBlogStats) {
list.add(e.text());
}
return list;
}
关于java - 如何在jsoup解析中选择类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20116098/