繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM