32

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.

P A N
  • 5,642
  • 15
  • 52
  • 103
Brian
  • 467
  • 3
  • 7
  • 10

1 Answers1

83

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')]
underrun
  • 6,713
  • 2
  • 41
  • 53
  • 6
    What does the dot mean in `contains(., 'testuser')`? – supertonsky Jul 02 '14 at 05:09
  • 12
    the dot in span[contains(., 'testuser')] is a span node ... inside a predicate (the square brackets), you can write xpath expressions relative to the node on which the predicate is being evalueated. so span[contains(., 'testuser')] evaluates the [] predicate on span nodes and checks itself for containing text 'testuser' ... alterantely, span[contains(./span, 'testuser')] tests will check spans inside spans, matching the outer span if the inner span contains 'testuser' ... its like directory paths. – underrun Jul 02 '14 at 18:23
  • what about `matches(...)` function for regular expressions? – Ahmad Jun 08 '15 at 12:08
  • why can't we use the expression `//span[contains(text(), 'testuser')]` to find span elements containing the word `testuser`? – Jinlxz Liu Oct 14 '21 at 04:09