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
  • 49,094
  • 5
  • 67
  • 90
sten
  • 6,266
  • 8
  • 35
  • 48

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
  • 98,039
  • 18
  • 159
  • 218
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
  • 49,094
  • 5
  • 67
  • 90
Bill Hileman
  • 2,730
  • 2
  • 15
  • 23
-1

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

Connor
  • 23
  • 4