簡體   English   中英

如何使用Jsoup通過ID查找元素?

[英]How to use Jsoup to find element by ID?

我正嘗試在Google新聞中抓取所有標題的“熱門新聞”部分。 為了僅在“熱門故事”部分中獲得標題,我必須縮小標簽范圍:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM