我正在尝试抓取谷歌新闻中的头条新闻部分的所有标题。为了仅获取“热门故事”部分中的标题,我必须缩小范围到此标签:
<div class="section top-stories-section" id=":2r">..</div>
这是我使用的代码(在 Eclipse 中):
public static void main(String[] args) throws IOException {
// fetches & parses HTML
String url = "http://news.google.com";
Document document = Jsoup.connect(url).get();
// Extract data
Element topStories = document.getElementById(":2r").;
Elements titles = topStories.select("span.titletext");
// Output data
for (Element title : titles) {
System.out.println("Title: " + title.text());
}
}
我似乎总是遇到 NullPointerException。当我尝试像这样访问热门故事时,它也不起作用:
Element topStories = document.select("#:2r").first();
我错过了什么吗?这不应该起作用吗?我对此比较陌生,请帮忙,谢谢!
最佳答案
从错误消息(实际查看页面)来看,div
标记不包含 id
属性。相反,您可以根据 CSS 类进行选择
Element topStories = document.select("div.section.top-stories-section").first();
关于java - 如何使用Jsoup通过ID查找元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894944/