【问题标题】:jsoup fetch element proceeding specific elementjsoup 获取元素处理特定元素
【发布时间】:2017-09-25 18:03:32
【问题描述】:

是否可以通过知道前一个元素来使用 jSoup 获取后续元素?

例如在这个html中,我有表格“Given this item”的数据
我想获取包含“正在寻找这个”的下一个表

<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

【问题讨论】:

    标签: jsoup


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      谢谢 TDG

      根据jsoup cookbook

      siblingA~siblingX: 查找在同级 A 之前的同级 X 元素,例如h1 ~ p

      所以我最终做了:

      table:contains(Given this item)  ~ table
      

      然后我拿了 e.first()

      【讨论】:

      • 这很奇怪 - 我尝试使用 ~ 但由于某种原因我没有得到预期的结果。
      • 请将此添加到您的解决方案中 - 我会接受。
      • 但这对我不起作用,所以我使用了答案中描述的方法。没有必要你会接受我的回答。如果您的解决方案有效,您应该接受它,这样其他用户就会知道它解决了您的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      相关资源
      最近更新 更多