【问题标题】:XPath to select an element after some marker (but before the next marker or the end)XPath 在某个标记之后(但在下一个标记或结尾之前)选择一个元素
【发布时间】:2014-11-25 23:27:13
【问题描述】:

我正在尝试从如下所示的表格中截取链接:

…
<table id="t">
  <tr><td>Section 1</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td><a href="some_link?for=one">View Report</a></td></tr>
  <tr><td>Section 2</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>No report for section three</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Section 3</td></tr>
  <tr><td>Nothing for section four either.</td></tr>
  <tr><td>Section 4</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td>Some content</td></tr>
  <tr><td><a href="some_link?for=four">View Report</a></td></tr>
  <tr><td>Some content</td></tr>
</table>
…

共有三个部分,但它们在表格中以线性方式而不是分层方式表示。每个部分可能有零个或一个链接,其文本是“查看报告”。

我可以使用什么 XPath 来选择对应于 Section n&lt;a&gt; 元素(如果不存在这样的元素,则为空集合)?

作为第一次剪辑,我考虑过

//table[@id='t']/tr[td='Section %d']/following-sibling::tr/td/a['View Report'][1]

(其中%dn 的占位符)。但是,这会错误地选择 n = 2 的最后一个链接。

我也可以试试

//table[@id='t']/tr[td='Section %d']/following-sibling::tr[following-sibling::tr/td='Section %d']/td/a['View Report'][1]

两个%d 占位符分别代表 nn + 1,但这不适用于最后一部分。此外,需要两个插值是不优雅的。有什么好的解决方案可以处理所有情况吗?

【问题讨论】:

    标签: xpath predicate


    【解决方案1】:

    向后做:找到前面的“Section Anything”是您要查找的“Section”的链接。

    //a["View Report"][../../preceding-sibling::tr[td[contains(.,"Section")]][1][.="Section 3"]]/@href
    

    【讨论】:

      【解决方案2】:

      如果没有与相关部分对应的&lt;a&gt; 元素,我不确定应该返回什么,但如果&lt;a&gt; 元素的前面部分带有值高于相关部分 - 对于 n = 2:

      //table[@id='t']/tr[td='Section 2']/following-sibling::tr/td[
        not(./parent::tr/preceding-sibling::tr[
             normalize-space(translate(td,'Section',''))>2])
             ]/a['View Report'][1]
      

      对于 n:

      //table[@id='t']/tr[td='Section n']/following-sibling::tr/td[
        not(./parent::tr/preceding-sibling::tr[
            normalize-space(translate(td,'Section',''))>n])
            ]/a['View Report'][1]
      

      【讨论】:

        猜你喜欢
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        • 2013-07-13
        • 2020-01-05
        • 2011-11-11
        相关资源
        最近更新 更多