Earlier, we had discussed XPath and its basics, and this post will look into the use of the text() function in detail. text() function is one of the many functions that can facilitate writing an XPath while locating an element in a webpage.
text() method is a function used to select the text node.
Now, what is a text node?
According to the documentation, A text node encapsulates XML character content. Or, in simpler terms, whatever is shown on a webpage comes under the text node.
So, we can use the text() function to search for any text shown on the webpage and locate the elements using it.
Let’s take a simple HTML document, as shown below:
<html> <head> </head> <body> <div> <p>Codekru Tutorials</p> </div> <div> <a class = "cr1" href = "https://www.codekru.com">Codekru Website link</a> <p>Guide to XPath in Selenium</p> </div> <div> <a href = "https://www.codekru.com/selenium">Selenium Link</a> </div> </body> </html>
Let’s locate the element containing “Codekru Tutorials” as text.
The below syntax can be used to write an XPath using the text() function –
If we don’t want to place a check on tag_name, then we can also use the below XPath –
* (star) is treated as a wildcard, and it means searching through everything depending on the location it is used. As we have used it after the double slash, it will search through every node, starting from the root node, to find the text we are looking for.
So, our final XPath using text() function would be –
or it could be
We can see that it selected the element(s) containing the text “Codekru Tutorials” is selected.
Few Points to remember
- text() method doesn’t search for a substring or a part of the text. It will only search for the whole text. So, we can’t search for the word “Tutorials” in our example using the text() node. Even if we try to do so, it won’t select any node(s).
If we want to search for a substring or a part of the text, we can use the contains() function.
- text() method doesn’t trim the whitespace on its own. This means if we have a node with text as “Codekru Tutorials “, we would have to use it with the whitespaces in the text() method. Using only “Codekru Tutorials” without any whitespace won’t work.
We can use the normalize-space() function to trim the string and then use it with the text() method.
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].