Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a web element by text with Selenium WebDriver, Java

I need to find the following element on the web page

<div class="b-datalist__item__addr">[email protected]</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 [email protected] text that is not a link so I can't use findElement(By.linkText()) command.

like image 642
Prophet Avatar asked Jun 04 '15 15:06

Prophet


People also ask

How can we get a text of a web element?

We can get the text from a website using Selenium webdriver USING the getText method. It helps to obtain the text for a particular element which is visible or the inner text (which is not concealed from the page).


2 Answers

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

Predicate [contains(text(),'[email protected]')] will match all of them

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

//div[starts-with(text(),'[email protected]')]

or fetch required element by exact text content:

//div[text()='[email protected]']
like image 145
Andersson Avatar answered Oct 19 '22 14:10

Andersson


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

//div[contains(text(),'[email protected]')]
like image 28
Saifur Avatar answered Oct 19 '22 15:10

Saifur