基于文本或属性中的字符串的硒查找元素

问题描述:

我正在尝试让Selenium根据可以包含在元素文本或任何属性中的字符串找到元素,并且我想知道是否可以实现一些通配符来捕获所有这些信息而不必使用multi条件或逻辑.我现在使用的有效的是...

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 ...

driver.findElement(By.xpath("//*[contains(@title,'foobar') or contains(.,'foobar')]"));

我想知道是否有一种方法可以使用通配符代替特定属性(@title),该属性也像OR条件的第二部分一样封装元素文本.

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.

这将提供包含文本的所有元素 foobar

This will give all elements that contains text foobar

driver.findElement(By.xpath("//*[text()[contains(.,'foobar')]]"));

如果您想要完全匹配,

driver.findElement(By.xpath("//*[text() = 'foobar']"));

或者您可以在Selenium中使用JQuery执行Javascript

Or you can execute Javascript using JQuery in Selenium

这会将所有包含文本的Web元素从父级返回到最后一个孩子,因此我正在使用jquery选择器:last 来获取包含此文本的最里面的节点,但这可能不会如果您有多个包含相同文本的节点,请始终保持准确.

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.

(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返回一个元素数组,如果页面上只有一个包含该特定文本的Web元素,则将得到一个元素数组.我正在做 .get(0)来获取数组的第一个元素,并将其转换为 WebElement

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

希望这会有所帮助.