[英]Selenium Find Element Based on String in Text or Attribute
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. 我试图让Selenium找到一个基于字符串的元素,该字符串可以包含在元素的文本或任何属性中,我想知道是否有一些通配符可以实现捕获所有这些而不必使用多条件OR逻辑。 What I'm using right now that works is ... 我现在正在使用的是......
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条件的第二部分那样。
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. jQuery返回一个Elements数组,如果页面上只有一个带有该特定文本的web元素,您将获得一个元素的数组。 I am doing .get(0)
to get that first element of the array and cast it to a WebElement
我正在做.get(0)
来获取数组的第一个元素并将其转换为WebElement
Hope this helps. 希望这可以帮助。
这将返回带有文本foobar
的元素
driver.findElement(By.xpath("//*[text()='foobar']"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.