Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Selenium WebDriver how to get Text from Span Tag

On Selenium Webdriver, how I can retrieve text from a span tag & print?

I need to extract the text UPS Overnight - Free

HTML code are as follow:

div id="customSelect_3" class="select_wrapper">
<div class="select_display hovered">
<span class="selectLabel clear">UPS Overnight - Free</span>

Using following code:

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span)).getText();
System.out.println(kk);

But above code is returning/printing text: 1.

like image 361
Onu Avatar asked Oct 08 '13 02:10

Onu


People also ask

How to get the text found within the span tag with selenium?

We can get the text found within the span tag with Selenium webdriver. The text of a web element can be captured with the method getText. Let us see an example of an element having the text - © Copyright 2021.

How to get the text of an element in Selenium WebDriver?

One such scenario is how to get the text of an element in Selenium. Selenium offers a getText () method used to get the text of an element, i.e.; it can be used to read text values of an element from a web page. In this article, we will understand how to get the text of an element using the getText () method offered by Selenium WebDriver.

How to read a text file in selenium with Python?

How to read a text file in Selenium with python? We can get the text found within the span tag with Selenium webdriver. The text of a web element can be captured with the method getText. Let us see an example of an element having the text - © Copyright 2021. All Rights Reserved enclosed within the span tag.

How to identify the element with span tag in HTML?

To identify the element with span tag, we have to first identify it with any of the locators like xpath, css, class name or tagname. After identification of the element, we can perform the click operation on it with the help of the click method. Then obtain its text with the text method.


2 Answers

Maybe the span element is hidden. If that's the case then use the innerHtml property:

By.css:

String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
              .getAttribute("innerHTML");

By.xpath:

String kk = wd.findElement(By.xpath(
                   "//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
              .getAttribute("innerHTML");

"/.//" means "look under the selected element".

like image 61
carlin.scott Avatar answered Sep 23 '22 14:09

carlin.scott


I agree css is better. If you did want to do it via Xpath you could try:

    String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText()))
like image 20
Sunita Venkatachalam Avatar answered Sep 21 '22 14:09

Sunita Venkatachalam