使用Xpath在html中搜索文本,并从下一个元素继续搜索,以便在javascript中进一步搜索

时间:2017-01-18 07:54:32

标签: javascript html xpath

<html>
    <body>

        <p>This is 
            <sub>subscripted</sub> 
            text1.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text2.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text3.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text4.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text5.
        </p>
    </body>
</html>

上面显示的是一个虚拟代码片段。我的要求是搜索"This is subscripted text1"。找到这个后,我必须从下一个<p>元素搜索另一个字符串匹配。如何使用xpath来满足此要求。或者提出任何其他想法

1 个答案:

答案 0 :(得分:0)

您正在寻找p轴上的同级following-sibling元素:

var p = document.evaluate('//p[normalize-space() = "This is subscripted text2."]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (p != null) {
  var siblingP = document.evaluate('following-sibling::p[normalize-space() = "This is subscripted text4."]', p, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  if (siblingP != null) {
    console.log(siblingP);
  }
}
<html>
    <body>
        <p id="p0">This is 
            <sub>subscripted</sub> 
            text4.
        </p>
        <p id="p1">This is 
            <sub>subscripted</sub> 
            text1.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text2.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text3.
        </p>
        <p id="p4">This is 
            <sub>subscripted</sub> 
            text4.
        </p>
        <p>This is 
            <sub>subscripted</sub> 
            text5.
        </p>
    </body>
</html>