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.
We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.
What Is getText() Method? The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. This method gets the visible, inner text (which is not hidden by CSS) of the web-element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With