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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…