jsoup fetch元素进行特定元素

时间:2017-09-25 18:03:33

标签: jsoup

通过了解前一个元素,是否可以使用jSoup获取前进元素?

例如在这个html中,我有表格的数据" 给定这个项目"
我想获取包含" 寻找此"的下一个表格。

<table><tr><td>irrelevant info 1 <a href="http://jsoup.org/">jsoup</a></td></tr></table>
<p>there is a p here</p>
<table><tr><td>Given this item <a href="http://jsoup.org/">jsoup</a></td></tr></table>
<p>there is a p here</p>
<table><tr><td>Looking for this <a href="http://jsoup.org/">jsoup</a></td></tr></table>
<p>there is a p here</p>
<table><tr><td>irrelevant info 2<a href="http://jsoup.org/">jsoup</a></td></tr></table>
<p>there is a p here</p>
<table><tr><td>irrelevant info 3 <a href="http://jsoup.org/">jsoup</a></td></tr></table>

例如: http://try.jsoup.org/~vtmUE0bVgNHSxdvpKcIzpL3pHEA

2 个答案:

答案 0 :(得分:1)

谢谢TDG

根据jsoup cookbook

siblingA~siblingX:找到兄弟A前面的兄弟X元素,例如: h1~p

所以我最终做了:

table:contains(Given this item)  ~ table

然后我拿了e.first()

答案 1 :(得分:1)

或者你可以使用list.indexOf

Elements tables = doc.select("table");// returns a list of all table elements
Element given = doc.select("table:contains(Given this item)").first(); //yor given element
Element required = tables.get(tables.indexOf(given)+1);//index of given + 1 = index of required element