簡體   English   中英

Jsoup Java For循環和元素

[英]Jsoup Java For Loops and Elements

我正在學習在Java中使用的jsoup。 首先,我不太了解jsoup“元素”和jsoup“元素”之間的區別以及何時使用它們。 這是我要執行的操作的示例。 使用此網址http://en.wikipedia.org/wiki/List_of_bow_tie_wearers#Architects我想解析“ Architects”類別下的文本名稱。 我已經試過了:

Document doc = null;
    try {
        doc = Jsoup.connect("http://en.wikipedia.org/wiki/List_of_bow_tie_wearers").get();
    } catch (IOException e) {

    }
    Elements basics = doc.getElementsByClass("mw-redirect");

    String text = basics.text();

    System.out.println(text);

}

這是輸出:

run:
Franklin Roosevelt Arthur Schlesinger, Jr. Reagan administration University of Colorado at Boulder Eric R. Kandel Eugene H. Spafford Arthur Schlesinger, Jr. middle finger John Daly Sir Robin Day Today show Tom Oliphant Today show Harry Smith TV chef Panic! At The Disco Watergate Watergate Hillary Clinton Donald M. Payne, Jr. Franklin Roosevelt Baldwin–Wallace College Howard Phillips Twilight Sparkle Gil Chesterton Bertram Cooper Richard Gilmore Dr. Donald "Ducky" Mallard, M.D., M.E. Medical Examiner Brother Mouzone hitman Buckaroo Banzai Conan Edogawa Jack Point Waylon Smithers Franklin Roosevelt NFL Chronicle of Higher Education Evening Standard

我真的只是想學習遍歷HTML文檔的基礎知識,但是我對jsoup菜譜有麻煩,因為它會使初學者感到困惑。 任何幫助表示贊賞。

關於第一個問題,顧名思義,Elements和Element之間的區別是項數。

類型為Element的對象包含一個HTML節點。 元素倍數類型之一。

如果您查看api文檔中有關ElementElements的構造函數,則它會變得很明顯。

現在到解析部分。 在您的代碼中,您正在尋找“ mw-redirect”,這還不夠。 您需要先“導航”到正確的部分。

我在這里做了一個工作樣本:

Document doc = null;
try {
    doc = Jsoup.connect("http://en.wikipedia.org/wiki/List_of_bow_tie_wearers").get();
} catch (IOException e) {

}

if (doc != null) {

    // The Architect headline has an id. Awesome! Let's select it.
    Element architectsHeadline = doc.select("#Architects").first();

    // For educational purposes, let's see what we've got there...
    System.out.println(architectsHeadline.html());

    // Now, we use some other selector then .first(), since we need to
    // get the tag after the h3 with id Architects.
    // We jump back to the h3 using .parent() and select the succeding tag
    Element architectsList = architectsHeadline.parent().nextElementSibling();

    // Again, let's have a peek
    System.out.println(architectsList.html());

    // Ok, now since we have our list, let's traverse it.
    // For this we select every a tag inside each li tag
    // via a css selector
    for(Element e : architectsList.select("li > a")){
      System.out.println(e.text());
    }
}

我希望這有幫助。

暫無
暫無

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

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