How to select a web element by text with Selenium

2019-02-09 08:29发布

问题:

I need to find the following element on the web page

<div class="b-datalist__item__addr">noreply@somedomain.com</div>

I'm coding with Java for Selenium WebDriver.
Need the exact CSS selector for this element to use it with driver.findElement(By.cssSelector(the-selector).click command.
div[class='b-datalist__item__addr'] selector is not good enough since I must search according to noreply@somedomain.com text that is not a link so I can't use findElement(By.linkText()) command.

回答1:

Css does not allow you do text based search. xpath is the only option there.

//div[contains(text(),'noreply@somedomain.com')]


回答2:

contains(node, substring) might solve the problem, but note that if there are several elements with similar text contents, e.g.

  • noreply@somedomain.com

  • office.noreply@somedomain.com

  • home.noreply@somedomain.com

Predicate [contains(text(),'noreply@somedomain.com')] will match all of them

In this case it's better to use starts-with(node, substring):

//div[starts-with(text(),'noreply@somedomain.com')]

or fetch required element by exact text content:

//div[text()='noreply@somedomain.com']