简体   繁体   中英

Creating an xPath to select a <p> element that has a <h3> preceding it

I'm looking to create an xpath that will target specific h3 titles on a page contained within the structure below, then select the sibling p tag that comes after:

<ul>
  <li> Title A
    <h3> Message A
    <p> Number A
  </li>
  <li> Title B
    <h3> Message B
    <p> Number B
  </li>
</ul>

I need to only select the p element if its preceding element is a h3 and matches a specific string.

I've come up with this so far:

/ul/li/h3[.="TELEPHONE:"]/following-sibling::text()[1]

Appreciate any advice why it may not be working.

You need to close <h3> tag and <p> tags

If I rewrite your example like that

<ul>
  <li>Title A
    <h3>Message A</h3>
    <p>Number A</p>
  </li>
  <li>Title B
    <h3>Message B</h3>
    <p>Number B</p>
  </li>
  <li>Title C
    <h3>Message C</h3>
    <p>Number C</p>
  </li>
</ul>

I can search what you need like

//li/h3[contains(text(), 'Message A')]/following-sibling::p

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