Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

java - Selenium Find Element Based on String in Text or Attribute

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...