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
.
This question is related to
java
html
selenium
selenium-webdriver
If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's 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();
Pythonic way to get text from Span tags:
driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text
You need to locate the element and use getText() method to extract the text.
WebElement element = driver.findElement(By.id("customSelect_3"));
System.out.println(element.getText());
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));
kk.getText().toString();
System.out.println(+kk.getText().toString());
PHP way of getting text from span tag:
$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();
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()))
Your code should read -
String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText();
Use CSS. it's much cleaner and easier.. Let me know if that solves your issue.
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".
Source: Stackoverflow.com