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
.
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.
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? 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.
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.
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".
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With