How to find by text in xpath?

by waino.konopelski , in category: HTML/CSS , a year ago

How to find by text in xpath?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mossie_beer , a year ago

@waino.konopelski 

To find an element by text in XPath, you can use the contains() function. The contains() function searches for a particular substring within the text of an element and returns true if the substring is found, and false if it is not.


For example, consider the following HTML code:

1
2
3
4
<div>
  <p>This is a paragraph with some text.</p>
  <p>This is another paragraph with some different text.</p>
</div>


To find the p element that contains the text "paragraph with some text", you could use the following XPath expression:

1
//p[contains(text(), 'paragraph with some text')]


This XPath expression will select the p element that has the specified text as a substring.


You can also use the contains() function to search for attribute values. For example, to find an element with an id attribute that contains the string "some-id", you could use the following XPath expression:

1
//*[contains(@id, 'some-id')]


This will select any element that has an id attribute with the specified substring.


I hope this helps! Let me know if you have any questions.