Retrieve an xpath text contains using text()

97,507

text() gets you a set of text nodes. I tend to use it more in a context of //span//text() or something.

If you are trying to check if the text inside an element contains something you should use contains on the element rather than the result of text() like this:

span[contains(., 'testuser')]

XPath is pretty good with context. If you know exactly what text a node should have you can do:

span[.='full text in this span']

But if you want to do something like regular expressions (using exslt for example) you'll need to use the string() function:

span[regexp:test(string(.), 'testuser')]
Share:
97,507
Brian
Author by

Brian

Updated on January 13, 2020

Comments

  • Brian
    Brian over 4 years

    I've been hacking away at this one for hours and I just can't figure it out. Using XPath to find text values is tricky and this problem has too many moving parts.

    I have a webpage with a large table and a section in this table contains a list of users (assignees) that are assigned to a particular unit. There is nearly always multiple users assigned to a unit and I need to make sure a particular user is assigned to any of the units on the table. I've used XPath for nearly all of my selectors and I'm half way there on this one. I just can't seem to figure out how to use contains with text() in this context.

    Here's what I have so far:

    //td[@id='unit']/span [text()='asdfasdfasdfasdfasdf (Primary); asdfasdfasdfasdfasdf, asdfasdfasdfasdf; 456, 3456'; testuser]
    

    The XPath Query above captures all text in the particular section I am looking at, which is great. However, I only need to know if testuser is in that section.