1

I'm using Selenium with xpath to get certain elements. I have a html page with the following elements:

<td>A</td>
<td><em>B</em></td>

I've tried using the following xpath expression to find td elements:

//td[contains(text(), 'A')] 
//td[contains(text(), 'B')]

The expression finds <td>A</td> but not <td><em>B</em></td>

How can I write an xpath expression which finds td tags with both no sub element and one or more sub elements?

magnusarinell
  • 1,127
  • 14
  • 22

3 Answers3

3

Try this instead

//td[contains(., 'A')]
//td[contains(., 'B')]

This will return the td tags. The difference between . and text() you can refer here - XPath: difference between dot and text().

Community
  • 1
  • 1
Grasshopper
  • 8,908
  • 2
  • 17
  • 32
  • Note that use of `contains()` here will also match `AA`, `A monkey`, etc. This may or may not be desirable. – kjhughes Sep 07 '16 at 12:37
1

You need to understand the difference between Testing text() nodes vs string values in XPath.

Here, you want to test the string value of td:

//td[. = 'B']

That way, both

<td>B</td>

and

<td><em>B</em></td>

will be selected, regardless of the em.

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

You can use ancestor to get the first <td> tag

//*[contains(text(), 'A')]/ancestor::td[1]
//*[contains(text(), 'B')]/ancestor::td[1]

And in general use

String text = "A";
driver.findElement(By.xpath("//*[contains(text(), '" + text + "')]/ancestor::td[1]"));
Guy
  • 46,488
  • 10
  • 44
  • 88