简体   繁体   English

如何创建一个 XPath 来查找按钮文本或按钮内嵌套元素的文本?

[英]How can I create an XPath that will look for button text or text from a nested element within the button?

I am using Selenium web driver in order to test out a button and this button can either have text like so我正在使用 Selenium web 驱动程序来测试一个按钮,这个按钮可以有这样的文本

<button>Foo</button>

Or it can look like this with nested tags of any type or depth.或者它可以看起来像这样,带有任何类型或深度的嵌套标签。

<button><span>Foo</span></button>

I tried doing我试着做

Driver.findElement(By.xpath(“//*[text()=“Foo”]”)); 

But this would only get the text in the immediate tag level.但这只会获得直接标记级别的文本。 I added a “//*” to the xpath and it would work for the nested element but then stop working for when the text is in the immediate level.我在 xpath 中添加了一个“//*”,它适用于嵌套元素,但在文本处于直接级别时停止工作。 I am looking for kind of OR condition or something where I can get this to work on both variations.我正在寻找一种 OR 条件或可以让它在两种变体上都起作用的东西。

I am using Java and selenium web driver.我正在使用 Java 和 selenium web 驱动程序。

Thanks in Advance,提前致谢,

Juan胡安

Try this:尝试这个:

driver.findElement(By.xpath("//button[contains(.,'Foo')]")); 

This will search for button element containing Foo text content in itself or any it child, exactly what you asking for.这将搜索包含Foo文本内容本身或任何它的子元素的button元素,这正是您所要求的。
BTW in Java we normally give objects names starting with non-capital letter, so it should be driver , not Driver there.顺便说一句,在 Java 中,我们通常给对象名称以非大写字母开头,所以它应该是driver ,而不是Driver那里。

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

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