使用jsoup从表的第一列获取数据

Geo*_*rge 1 html java html-table html-parsing jsoup

为了我的问题,我创建了一个简单的 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>
Run Code Online (Sandbox Code Playgroud)

我想使用 Jsoup 从名为“Fruit”的第一列中提取数据。因此,结果应该是:

Apples
Oranges
Run Code Online (Sandbox Code Playgroud)

我写了一个程序,摘录如下:

//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());
}
Run Code Online (Sandbox Code Playgroud)

这个程序的结果是:

Apples
Carrots
Oranges
Peas
Run Code Online (Sandbox Code Playgroud)

我知道有些东西不好用,但我找不到我的错误。Stack Overflow 中的所有其他问题都没有解决我的问题。我需要做什么?

Psh*_*emo 5

你似乎在寻找

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

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

:eq(n): 查找同级索引等于 的元素n;例如form input:eq(1)

因此,td:eq(0)我们选择每个<td>是其父级的第一个子级- 在这种情况下<tr>