On Selenium WebDriver, how to get text from a Span tag

In Selenium Webdriver, how can I extract text from a span tag and print it?
I need to extract the text - "UPS seven days a week - for free"

The HTML is as follows:
div id="customSelect_3" class="select_wrapper"> <div class="select_display hovered"> <span class="selectLabel clear">UPS Overnight - Free</span>

Using the following code:

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

But above the code returns / prints the text - "1" .

+8
java html selenium selenium-webdriver
source share
8 answers

I agree css is better. If you want to do this via Xpath, you can try:

  String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText())) 
+6
source share

Your code should read -

 String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText(); 

Use CSS. it is much cleaner and simpler. Let me know if this solves your problem.

+3
source share

If you prefer to use xpath and this range is the only span below your div, use my example below. I would recommend using CSS (see sircapsalot post).

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

Css example:

 String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText(); 
+2
source share

Maybe the span element is hidden. If the innerHtml property is used in this case:

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

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

+2
source share
 String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span)); 
.

kk.getText () ToString (); System.out.println (+ kk.getText () ToString ().);

0
source share

Pythonic way to get text from Span tags:

 driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text 
0
source share

PHP way to get text from span tag:

 $spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText(); 
0
source share

You need to find the element and use the getText () method to extract the text.

 WebElement element = driver.findElement(By.id("customSelect_3")); System.out.println(element.getText()); 
0
source share

All Articles