简体   繁体   English

在 Selenium 测试中使用 XPath 按文本获取 WebElement

[英]Getting WebElement by Text using XPath in Selenium test

I would like to find any WebElement based on text using XPath.我想使用 XPath 查找基于文本的任何 WebElement。

WebElement that I am interested to find,我有兴趣找到的 WebElement,

我感兴趣的 WebElement

Its HTML,它的 HTML,

它的 CSS

Basically my WebElement that I am trying to retrieve by Text contains an input element.基本上,我试图通过 Text 检索的 WebElement 包含一个输入元素。

I currently use,我目前使用,

driver.findElement(By.xpath("//*[normalize-space(text()) = 'Own Hotel']"));

which does not find the WebElement above, but it usually works to retrieve all other web elements.它没有找到上面的 WebElement,但它通常可以检索所有其他 Web 元素。

Even,甚至,

By.xpath("//*[contains(text(),'Own Hotel')]")

did not give me any results.没有给我任何结果。 Although I am interested in exact text match.虽然我对精确的文本匹配感兴趣。

I am looking for a way to find web element by text immaterial of the elements that are present inside the web element.我正在寻找一种方法来通过 web 元素中存在的元素的文本无关紧要来查找 web 元素。 If text matches, it should return the WebElement.如果文本匹配,则应返回 WebElement。

Thanks!谢谢!

It seems text is wrapped inside a label and not input.似乎文本被包裹在标签内而不是输入。 Try this尝试这个

driver.findElement(By.xpath(".//label[text()[normalize-space() = 'Own Hotel']]"));

There is nice explanation about this xpath pattern here有关于这个XPath模式很好的解释在这里

In the HTML below:在下面的 HTML 中:

HTML

The innerText Own Hotel within the <input> node contains a lot of white-space characters in the beginning as well at the end. <input>节点中的innerText Own Hotel在开头和结尾都包含许多空白字符。 Due to the presence of these leading and trailing white-space characters you can't use the location path text() as:由于存在这些前导和尾随空白字符,您不能将位置路径text()用作:

text() selects all text node children of the context node text()选择上下文节点的所有文本节点子节点


As an alternative, you need to use the String Function string normalize-space(string?) as follows:作为替代方案,您需要使用字符串函数string normalize-space(string?) ,如下所示:

driver.findElement(By.xpath("//*[normalize-space()='Own Hotel']"));

However, it would a better idea to make your search a bit more granular adding the tagName and preferably an unque attribute as follows:但是,最好让您的搜索更加细化,添加tagName并最好添加一个 unque 属性,如下所示:

  • Using tagName and normalize-space() :使用tagNamenormalize-space()

     driver.findElement(By.xpath("//input[normalize-space()='Own Hotel']"));
  • Using tagName , and normalize-space() :使用tagNamenormalize-space()

     driver.findElement(By.xpath("//input[@name='ownHotel' and normalize-space()='Own Hotel']"));

References参考

you can find a couple of relevant discussions using normalize-space() in:您可以在以下位置使用normalize-space()找到一些相关讨论:

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

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