Selenium and xPath - locating a link by containing text

0
0

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?

  • You must to post comments
0
0

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 (.).

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website