【问题标题】:How can I match an <a> tag based on the text that precedes it?如何根据前面的文本匹配 <a> 标记?
【发布时间】:2019-12-15 01:16:38
【问题描述】:

我有以下 HTML:

<html>
    <body>
        I do not want this link here <a href="blah">link text</a>
        But I want this one here <a href="blah blah">more link text</a>
    </body>
</html>

我正在尝试仅获取第二个 &lt;a&gt; 标记,并且正在使用以下内容:

//*[contains(.,"But I want this one here ")]/a

返回

<a href="blah">link text</a>
<a href="blah blah">more link text</a>

我只想

<a href="blah blah">more link text</a>

【问题讨论】:

  • 那么您是在寻找文本I want this one here 后面的元素还是只是第二个链接?
  • 我想要But I want this one here文本后面的元素

标签: html xml xpath


【解决方案1】:

这个 XPath,

//text()[normalize-space()="But I want this one here"]/following-sibling::*[1]

将选择紧跟在"But I want this one here"之后的元素,

<a href="blah blah">more link text</a>

根据要求。

【讨论】:

    【解决方案2】:

    获取下面&lt;a&gt;href属性值的一种方法是

    //text()[contains(.,"But I want this one here ")]/following-sibling::a/@href
    

    它的输出是

    blah blah
    

    要仅检索元素节点,请省略 /@href

    【讨论】:

      【解决方案3】:

      试试

      //*[contains(following-sibling::text()[1],"But I want this one here")]/following-sibling::a
      

      【讨论】:

        猜你喜欢
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 2020-06-18
        • 2019-12-30
        • 2021-11-03
        相关资源
        最近更新 更多