Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath contains text() doesnt work with comments

Can someone please explain why i cant find h2 which contains text? Piece of html i am looking for

<h2 class="heading">
    <!---->
    "Some text"
    <!---->
</h2>

Tried to use already

//*[contains(text(),'Some text')]

But it does not find it.

Edit: Looks like issue is due to shadow-root element. Using your methods still did not help me to find the element. But now atleast i know i can use your methods in different places

like image 395
Zantok Avatar asked Jul 14 '26 20:07

Zantok


1 Answers

Your problem illustrates a general rule: you very rarely need to use the text() expression. Nearly all the time, using string() to get the string value of an element is better; and most of the time you don't even need to call string(), because when a string is needed, you can supply a node and its string value will automatically be extracted.

So you can write

//*[contains(string(),'Some text')]

or more simply

//*[contains(.,'Some text')]

The string value of an element (obtained using the string() function) is the concatenation of all its descendant text nodes.

This does have the drawback that if an h2 element contains "Some text", then all the ancestors of the h2 element also contain "Some text". So you may want to be more selective about which elements you search for.

like image 149
Michael Kay Avatar answered Jul 18 '26 04:07

Michael Kay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!