Selenium Find Element Based on String in Text or Attribute

爷,独闯天下 提交于 2021-02-16 04:27:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!