2

I want to find element with XPath in Selenium, which contain text, but has two possible cases. Here there are :

.//li/a[contains(., 'blah')]
.//li/a/span[contains(., 'blah')]

How to cover the two cases with single XPath?

Second question if possible I want to get as result pointer to the a element, not to the span in both cases.

Also, is there a general way to return as a match parent of the matched element, instead ?

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
sten
  • 7,028
  • 9
  • 41
  • 63

3 Answers3

4

In general, XPaths expressions can be combined with | (eg: xpath1 | xpath2), however you don't really need to do so in this case...

As Josh Crozier asks in the comments, yes, .//li/a[contains(., 'blah')] covers both cases.

The string value of a necessarily will contain "blah" if any of its descendant span element's string values contain "blah".

Second question if possible I want to get as result pointer to the a-element, not to the span in both cases.

.//li/a[contains(., 'blah')] will return such a elements.

Be aware that it will also return such a elements as

 <a>xxxblah</a>
 <a><span>blah</span></a>
 <a><span>bl</span><span>ah</span></a>

PS> BTW is there a general way to return as a match parent of the matched element, instead ?

Well, appending /.. to an XPath will return the parent, but I suspect you'd benefit from learning about the string value of XML elements. See Testing text() nodes vs string values in XPath

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
2

You should test the xpath I'm giving you to make sure it doesn't return more matches than you want, but I'd just use: //a[contains(.,'blah')]

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
-1

You can try something like this .//li/*[contains(., 'blah')]

Connor
  • 33
  • 1
  • 6