Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locate a span with a specific text in Selenium? (Using Java)

I'm having trouble locating a span element in Selenium using java.

the HTML looks like:

<div class="settings-padding">
<span>Settings</span>
</div>

And I've tried the following with no luck:

By.xpath("span[.='Settings']")

and

By.xpath("span[text()='Settings']")

and

By.cssSelector("div[class='settings-padding']"))

as well as some other similar attempts. Could you point me to the best method to do this? As it stands I constantly get "Unable to locate element" error in eclipse.

like image 286
HosseinK Avatar asked Jul 22 '16 19:07

HosseinK


People also ask

How can you check whether a particular text present on a webpage in Selenium?

There are more than one ways to find it. We can use the getPageSource() method to fetch the full page source and then verify if the text exists there. This method returns content in the form of string. We can also check if some text exists with the help of findElements method with xpath locator.

What is the easiest way to get the value from a text field in Selenium?

We can get the entered text from a textbox in Selenium webdriver. To obtain the value attribute of an element in the html document, we have to use the getAttribute() method. Then the value is passed as a parameter to the method.

How do you search for text in WebElement?

We can get text from a webelement with Selenium webdriver. The getText() methods obtains the innerText of an element. It fetches the text of an element which is visible along with its sub elements.


2 Answers

Your all xpath are looks OK, Just some syntactically incorrect. you are missing // in your xpath

The correct xpath are as below :-

By by = By.xpath("//span[.='Settings']")

Or

By by = By.xpath("//span[text()='Settings']")

Or

By by = By.xpath("//div[@class='settings-padding']/span"))

Or you can use cssSelector as :-

By by = By.cssSelector("div.settings-padding > span"))

Using anyone of the above By locator you can locate element as below :-

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(presenceOfElementLocated(by));

Hope it helps...:)

like image 181
Saurabh Gaur Avatar answered Sep 22 '22 02:09

Saurabh Gaur


For the element below

<span class="test-button__text">
    Test Text
</span>

The following solution works for me

driver.find_element_by_xpath("//span[contains(@class, 'test-button__text') and text()='Test Text']")
like image 33
Vikki Avatar answered Sep 26 '22 02:09

Vikki