Selenium Find an item based on a string in text or attribute

I am trying to find a Selenium element based on a string that may be contained in the element text or any attribute, and I am wondering if any template can be used to capture all this without having to use multi - condition OR logic. What I'm using now works ...

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

And I wanted to know if there is a way to use a wildcard instead of a specific attribute (@title), which also encapsulates the text of the element, like the second part of the OR condition.

+5
source share
2 answers

This will give all elements containing foobar text

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

If you want an exact match,

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

Or you can execute javascript using jQuery in Selenium

This will return all web elements containing text from parent to last child, so I use the jQuery :last selector to get the innermost node containing this text, but this may not always be accurate if you have multiple nodes containing one and the same text.

 (WebElement)((JavascriptExecutor)driver).executeScript("return $(\":contains('foobar'):last\").get(0);"); 

If you need an exact match with the above, you need to run a filter by 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 there is only one web element on the page with this specific text, you will get an array of one element. I am doing .get(0) to get this first element of an array and pass it to WebElement

Hope this helps.

+10
source

This will return an element with text foobar

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

All Articles