简体   繁体   中英

Xpath to find all elements following specific node

I have a specific html as shown below and i had observed that there is one specific h2 node that appears in all cases.

<div id='myDiv'> 
<..other elements..>
  <h2>Locator</h2>  
        <h3>Header 1 </h3>  
        <p>Paragraph 1.1</p>    
        <h3>Header 2 </h3>  
        <p>Paragraph 2.1</p>  
        <p>Paragraph 2.2.</p>  
        <p>Paragraph 2.3.</p> 
        <h4> test header 4</h4>
</div> 

I want all the markups after the specific node the html format is as below. As you can see i can locate the h2 tag by applying xpath //div[@id='myDiv']/h2[contains(.,"Locator")] but the trouble is finding all elements inside the div following the h2 tag.(I am not sure what types of tags can come after this h2 tag).Just to be more clear, What is the xpath to get the following nodes selected

<h3>Header 1 </h3>  
<p>Paragraph 1.1</p>    
<h3>Header 2 </h3>  
<p>Paragraph 2.1</p>  
<p>Paragraph 2.2.</p>  
<p>Paragraph 2.3.</p> 
<h4> test header 4</h4>

*[preceding-sibling::h2] indicates all elements after h2 . So after adding contains in the selector it goes like this

//div[@id='myDiv']/*[preceding-sibling::h2[contains(text(),'Locator')]]

See Demo Here . Click The Test button you will get the result

You appear to be looking for the following-sibling axis:

//div[@id='myDiv']/h2[contains(.,"Locator")]/following-sibling::*

Note, however, that the following siblings are, indeed, siblings of the nodes selected by the previous step in the path. In your example, that's exactly what all the elements you want to select are (with respect to the h2 node), but if any of those nodes had child elements, those child elements would not be siblings to the h2 , and would not be selected.

If you want all those child elements as well, and their children, etc., then you could use the descendant-or-self axis, too:

//div[@id='myDiv']/h2[contains(.,"Locator")]/following-sibling::*/descendant-or-self::*

我会将//h2[contains(text(),"Locator")]/following-sibling::*用于嵌套在与h2相同父级下但比h2“低”的所有标记。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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