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?
text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.
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.
So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));
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"));
I think the problem is here:
[contains(text()='Some text')]
To break this down,
[]
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. text()
is a selector
that matches all of the text nodes that are children of the context
node -- it returns a node set. 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')]]
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.
The inner []
are a conditional that operates on each node in that
node set.
contains
is a function that operates on a string. Here it is passed
an individual text node (.
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With