2015-03-13 72 views
1

我正在學習jsoup在java中使用。首先,我並不真正理解jsoup「Elements」和jsoup「Element」之間的區別以及何時使用它們。這是我想要做的一個例子。使用這個URL http://en.wikipedia.org/wiki/List_of_bow_tie_wearers#Architects我想分析「Architects」類別下的文本名稱。我已經試過這樣:Jsoup爪哇循環和元素

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食譜麻煩因爲這對於初學者來說是令人困惑的。任何幫助表示讚賞。

回答

4

關於你的第一個問題,元素和元素之間的區別是,如名稱所示,項目的數量。

Element類型的對象包含一個HTML節點。其中一個類型的元素多個。

如果您看看ElementElements的API文檔中的構造函數,它就變得相當明顯。

現在是解析部分。在你的代碼中你正在尋找「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()); 
    } 
} 

我希望這有助於。

+0

哦,我忘了提及,最後一個循環隱式使用「元素」。如果您沒有注意到,.select()本身會返回Elements類型的元素列表。 :-) – 3stadt 2015-03-13 15:16:22

+0

謝謝。我知道這是非常基本的信息,所以我很感激你花時間解釋。 – 2015-03-13 15:20:54

+0

出於好奇,我想知道是否有辦法包含或排除某些事情。例如,這個輸出打印出「哈佛」一詞,因爲它包含在「沃爾特格羅皮烏斯」部分末尾的一個「a」元素中的文本中。另一個例子是,由於我們選擇了「Architect」頭文件的nextelementsibling,因此列表中的姓氏「Owen Luder」不包含在內。看起來,「歐文·盧德」與其餘的不在同一個無序列表中,並在稍後加以討論。最後,我也不知道我們如何得到嵌套在那裏的日期和描述。 – 2015-03-18 16:30:41