2016-03-30 39 views
0

的第一列,我的問題的目的數據,我創建了一個簡單的HTML頁面,提取其中的是以下幾點:使用jsoup擺脫表

<table class="fruit-vegetables"> 
    <thead> 
    <th>Fruit</th> 
    <th>Vegetables</th> 
    </thead> 
    <tbody> 
    <tr> 
     <td> 
     <b> 
      <a href="https://en.wikipedia.org/wiki/Apple" title="Apples">Apples</a> 
     </b> 
     </td> 
     <td> 
     <a href="https://en.wikipedia.org/wiki/Carrot" title="Carrots">Carrots</a> 
     </td> 
    </tr> 
    <tr> 
     <td> 
     <i> 
      <a href="https://en.wikipedia.org/wiki/Orange_%28fruit%29" title="Oranges">Oranges</a> 
     </i> 
     </td> 
     <td> 
     <a href="https://en.wikipedia.org/wiki/Pea" title="Peas">Peas</a> 
     </td> 
    </tr> 
    </tbody> 
</table> 

我想從數據中提取第一列使用Jsoup命名爲「Fruit」。因此,結果應該是:

Apples 
Oranges 

我已經編寫的程序,提取物,其是下列:

//In reality, it should be connect(html).get(). 
//Also, suppose that the String `html` has the full source code. 
Document doc = Jsoup.parse(html); 

Elements table = doc.select("table.fruit-vegetables").select("tbody").select("tr").select("td").select("a"); 

for(Element element : table){ 
    System.out.println(element.text()); 
} 

這個程序的結果是:

Apples 
Carrots 
Oranges 
Peas 

我知道有些事情不太好,但我找不到我的錯誤。 Stack Overflow中的所有其他問題都沒有解決我的問題。我需要做什麼?

回答

0

你似乎在尋找

Elements el = doc.select("table.fruit-vegetables td:eq(0)"); 
for (Element e : el){ 
    System.out.println(e.text()); 
} 

http://jsoup.org/cookbook/extracting-data/selector-syntax你可以找到的:eq(n)描述爲

:eq(n):查找其同胞關係指數等於n元素;例如form input:eq(1)

因此,在這種情況下td:eq(0)我們選擇每個td這是它的父(tr)的第一個孩子。

+0

你的回答幫了我很多東西來解決我的問題。非常感謝你。 – George