1
votes

I have this xpath expression that does not work

"//div[child[0]::h4[text()[contains(.,'Dir')]]]/a"

To parse this html:

<div class="txt"> 
      <h4 class="c1"> 
        Dir
      </h4> 
    <a  href="/name/myname/">Bob</a>
</div> 

I am trying to get at the link node (a). There are other html tags in the document with the same div/h4 hierarchy, with the only difference being the innertext of the h4 tag. So how do I check that the div class (1) has a sub h4 node with inner text "dir" AND (2) get the first link node (a). Do not assume the link is the next sibling of h4.

2
You were very close, except that you can't put a predicate on an axis, so child[0]:: is incorrect. If you wanted the first h4 child of div, you could use //div[child::h4[1][text()[...]]/a, or just //div[h4[1][text()[...]]/a since child:: is implicit for elements. If the h4 must be the first element child, then //div[*[1]/self::h4[...]]/a. - LarsH

2 Answers

2
votes

Couldn't you just use this xpath?

"//div[h4[contains(text(),'Dir')]]/a"

child[0] is not a valid axis AFAIK so it fails.

I don't know if this alone would satisfy your conditions without seeing a more complete example HTML. But this certainly works for this one.

If it's possible that there are multiple h4 elements within the div and you only want to check the first:

"//div[h4[1][contains(text(),'Dir')]]/a"
1
votes

How do I check that the div class (1) has a sub h4 node with inner text "dir" AND (2) get the first link node (a)

use:

"//div[@class='txt' and h4[contains(.,'Dir')]]/a[1]"