[英]Using jsoup to get data from first column of table
就我的問題而言,我創建了一個簡單的HTML頁面,其摘錄如下:
<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
我知道有些事情行不通,但是我找不到我的錯誤。 堆棧溢出中的所有其他問題都無法解決我的問題。 我需要做什么?
您似乎在尋找
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)
:eq(n)
:查找兄弟索引等於n
元素; 例如,form input:eq(1)
因此,使用td:eq(0)
來選擇每個<td>
,它是其父級的第一個子級 -在這種情況下為<tr>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.