简体   繁体   English

如何使用Xpath根据其父级兄弟姐妹的孩子的文本查找元素

[英]How to find an element based on its parent's sibling's child's text with Xpath

Having a piece of html document like this: 有一块这样的html文件:

<div class="main">
   <div class="first">
         **<div id="my_target"></div>**
    </div>
    <div class="second">
       <p class="child">I need to find  preceding or nearest sibling's child with id=my_target based on this text</p>
       <div>...</div>
        <div/>
    <div>....</div>
   </div>

Can someone help me to find an element with id=my_target and having parent whose sibling's child element p contains some specific text using XPath? 有人可以帮我找到一个id=my_target的元素,并使用XPath让其父级的子级元素p包含某些特定文本的父级吗?

Following your explanation step by step: 按照您的说明逐步操作:

//div[@id="my_target" and ../following-sibling::div/p="some text"]

Demo (using xmllint ): 演示(使用xmllint ):

$ cat test.html
<div class="main">
   <div class="first">
         <div id="my_target">This is what I want to find</div>
    </div>
    <div class="second">
       <p class="child">some text</p>
       <div>...</div>
    </div>
    <div>....</div>
</div>
$ xmllint test.html --xpath '//div[@id="my_target" and ../following-sibling::div/p="some text"]'
<div id="my_target">This is what I want to find</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM