问题
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')]"));
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.
回答1:
This will give all elements that contains text 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
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 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
Hope this helps.
回答2:
This will return the element with text foobar
driver.findElement(By.xpath("//*[text()='foobar']"))
来源:https://stackoverflow.com/questions/32259865/selenium-find-element-based-on-string-in-text-or-attribute