Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (47.6k points)

I'm trying to use XPath to find an element containing text, but I am not able to get it.

I used the below code:

WebElement searchItemByText = driver.findElement(By.xpath("//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text()='Some text')]"));

If I remove the last bit with the "contains" thing, it locates my span element, but I need to select it based on the text contents. It's not gonna be a perfect match of 'Some text' either because it might contain truncated strings as well.

plz tell me the issue

1 Answer

0 votes
by (106k points)

The problem you are facing is because:

[contains(text()='Some text')]

To get rid of this error try to change it to the following:-

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

  1. Here the outer [ ] are a conditional that operates on each individual node in that node you can set function text()as a selector that matches all of the text nodes that are children of the context node and it returns a node-set.

  2. Whereas the inner [ ] is a conditional which operates on each node in that node-set.

  3. The function contains()  operates on a string. Here it is passed an individual text node (.).

If you want to Learn What is Selenium visit this Selenium Training by Intellipaat.

Browse Categories