简体   繁体   English

如何使用xpath查找带有可选子元素的元素?

[英]How can I use xpath to find element with optional sub element?

I'm using Selenium with xpath to get certain elements. 我正在使用Selenium和xpath来获取某些元素。 I have a html page with the following elements: 我有一个包含以下元素的html页面:

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

I've tried using the following xpath expression to find td elements: 我尝试使用以下xpath表达式来查找td元素:

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

The expression finds <td>A</td> but not <td><em>B</em></td> 表达式找到<td>A</td>但不是<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? 如何编写一个xpath表达式,找到没有子元素和一个或多个子元素的td标签?

Try this instead 试试这个

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

This will return the td tags. 这将返回td标签。 The difference between . 和...之间的不同 。 and text() you can refer here - XPath: difference between dot and text() . 和text()你可以在这里参考 - XPath:点和文本之间的差异()

You need to understand the difference between Testing text() nodes vs string values in XPath . 您需要了解 测试text()节点与XPath中的字符串值之间的区别。

Here, you want to test the string value of td : 在这里,您要测试td的字符串值:

//td[. = 'B']

That way, both 那样,两者兼而有之

<td>B</td>

and

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

will be selected, regardless of the em . 将被选中,无论emem

You can use ancestor to get the first <td> tag 您可以使用ancestor来获取第一个<td>标记

//*[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]"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM