2015-03-13 59 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