Angelina Proft
Angelina Proft

Reputation: 3

How to extract the text of the outer span using Selenium WebDriver and Java

I'm facing a problem, where I'm unable to get the text of a span tag that has another span tag as a child:

<span class="abc">
        <span class="def">Inner Span</span> 
        Outer Span
</span>

When I'm using

driver.findElement(By.cssSelector(".abc")).getText()

Selenium returns "Inner Span" as well as "Outer Span". I guess innerText is used here. But I only need the text "Outer Span" of the outer span with the class "abc".

Upvotes: 0

Views: 1199

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

The text Outer Span is a Text Node and is the lastChild of the parent <span> node. So extract the text you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using cssSelector:

    System.out.println(((JavaScriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.abc")))).toString());
    
  • Using xpath:

    System.out.println(((JavaScriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='abc']")))).toString());
    

Upvotes: 1

KunduK
KunduK

Reputation: 33384

Try JavascriptExecutor and get the textContent of lastChild

Induce WebDriverWait() and wait for visibilityOfElementLocated()

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='abc']")));
JavascriptExecutor js= (JavascriptExecutor) driver; 
String strtext=(String) js.executeScript("return arguments[0].lastChild.textContent;", element);
System.out.println(strtext.trim());

Or you can split lines and get the desire value using Index.

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='abc']")));
String text=element.getAttribute("textContent");
String[] lines = text.split("\\r?\\n");
System.out.println(lines[2].trim());

Upvotes: 0

Related Questions