【问题标题】:How to use Jsoup to find element by ID?如何使用 Jsoup 通过 ID 查找元素?
【发布时间】:2014-02-19 23:33:22
【问题描述】:

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

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

我错过了什么吗?这不应该工作吗?我对此比较陌生,请帮助并感谢您!

【问题讨论】:

    标签: java html eclipse web-scraping jsoup


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这样可行。但是有两个问题:那个 div 标签怎么不包含 id 属性(它清楚地写着 'id=":2r"')?如果完整的类名是“section top-stories-section”而不仅仅是“top-stories-section”,为什么这会起作用?我是新手,所以我对学习很感兴趣。非常感谢!
    • 如前所述,原始错误表明它找不到:2r 元素,因此不确定您最初是从哪里得到的。 2) 仅适用于任一 css 类。已更新以同时显示 2 个类 - 更正确:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2019-10-11
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2021-12-23
    • 2017-05-02
    相关资源
    最近更新 更多