Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium and xPath - locating a link by containing text

Tags:

I'm trying to use xPath to find an element containing a piece of text, but I can't get it to work....

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.

Anyone see the issue?

like image 565
joakimnorberg Avatar asked Apr 15 '14 08:04

joakimnorberg


People also ask

Can XPath locate element using text?

text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.

How do I find the text in an element with a link?

We can find an element using the link text or the partial link text in Selenium webdriver. Both these locators can only be applied to elements with the anchor tag. The link text locator matches the text inside the anchor tag. The partial link text locator matches the text inside the anchor tag partially.

How do I search for text in XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

How do you select a link to text in Selenium?

In order to access link using link text in Selenium, the below-referenced code is used: driver. findElement(By. linkText("this is a link text"));


1 Answers

I think the problem is here:

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

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

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

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

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

like image 147
dnlcrl Avatar answered Sep 18 '22 22:09

dnlcrl