使用 jsoup 从 table 的第一列获取数据
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
我知道有些地方不太对劲,但我找不到我的错误。 Stack Overflow 中的所有其他问题都没有解决我的问题。我必须做什么?
您似乎在寻找
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)
: find elements whose sibling index is equal to n
; e.g. form input:eq(1)
因此,对于 td:eq(0)
,我们选择每个 <td>
,这是其父项的 第一个子项 - 在本例中为 <tr>
。
为了我的问题,我创建了一个简单的 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
我知道有些地方不太对劲,但我找不到我的错误。 Stack Overflow 中的所有其他问题都没有解决我的问题。我必须做什么?
您似乎在寻找
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)
: find elements whose sibling index is equal ton
; e.g.form input:eq(1)
因此,对于 td:eq(0)
,我们选择每个 <td>
,这是其父项的 第一个子项 - 在本例中为 <tr>
。