如何使用Jsoup按ID查找元素?

时间:2014-02-19 23:33:22

标签: java html eclipse web-scraping jsoup

我正试图在Google新闻中搜索所有标题的热门故事部分。为了只获得Top Stories部分中的标题,我必须缩小到这个标签:

<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();

我错过了什么吗?这不应该有效吗?我对此比较陌生,请帮忙谢谢!

1 个答案:

答案 0 :(得分:0)

根据错误消息(实际查看页面)判断div标记不包含id属性。相反,您可以根据CSS类选择

Element topStories = document.select("div.section.top-stories-section").first();