Java Selenium 基于文本或属性中的字符串查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32259865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium Find Element Based on String in Text or Attribute
提问by user2150250
I'm trying to have Selenium find an element based on a string that can be contained in the element's text or any attribute, and I'm wondering if there's some wildcard I can implement to capture all this without having to use multi-condition OR logic. What I'm using right now that works is ...
我试图让 Selenium 基于可以包含在元素文本或任何属性中的字符串找到一个元素,我想知道是否有一些通配符可以实现来捕获所有这些,而不必使用多条件或逻辑。我现在正在使用的有效的是......
driver.findElement(By.xpath("//*[contains(@title,'foobar') or contains(.,'foobar')]"));
And I wanted to know if there's a way to use a wildcard instead of the specific attribute (@title) that also encapsulates element text like the 2nd part of the OR condition does.
我想知道是否有一种方法可以使用通配符而不是特定属性 (@title),它也像 OR 条件的第二部分那样封装元素文本。
回答by LINGS
This will give all elements that contains text foobar
这将给出包含文本的所有元素 foobar
driver.findElement(By.xpath("//*[text()[contains(.,'foobar')]]"));
If you want exact match,
如果你想要精确匹配,
driver.findElement(By.xpath("//*[text() = 'foobar']"));
Or you can execute Javascript using JQuery in Selenium
或者您可以在 Selenium 中使用 JQuery 执行 Javascript
This will return all web elements containing the text from parent to the last child, hence I am using the jquery selector :last
to get the inner most node that contains this text, but this may not be always accurate, if you have multiple nodes containing same text.
这将返回包含从父级到最后一个子级的文本的所有 web 元素,因此我使用 jquery 选择器:last
来获取包含此文本的最内部节点,但这可能并不总是准确的,如果您有多个节点包含相同的文本.
(WebElement)((JavascriptExecutor)driver).executeScript("return $(\":contains('foobar'):last\").get(0);");
If you want exact match for the above, you need to run a filter on the results,
如果您想与上述完全匹配,则需要对结果运行过滤器,
(WebElement)((JavascriptExecutor)driver).executeScript("return $(\":contains('foobar')\").filter(function() {" +
"return $(this).text().trim() === 'foobar'}).get(0);");
jQuery returns an array of Elements, if you have only one web element on the page with that particular text you will get an array of one element. I am doing .get(0)
to get that first element of the array and cast it to a WebElement
jQuery 返回一个元素数组,如果页面上只有一个包含该特定文本的 Web 元素,您将获得一个包含一个元素的数组。我正在.get(0)
获取数组的第一个元素并将其转换为WebElement
Hope this helps.
希望这可以帮助。
回答by Shubhasmit Gupta
This will return the element with text foobar
这将返回带有文本的元素 foobar
driver.findElement(By.xpath("//*[text()='foobar']"))