XPath contains text: Finding xPath for an element with text

907    Asked by AlexanderCoxon in Devops , Asked on Apr 5, 2021

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

Here is the code I am using:

 

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

Answered by Alexander Coxon

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')]]

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.

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

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



Your Answer

Interviews

Parent Categories