-1

I want to print the text of the span element ( Afghanistan ), but when I use the path of the span ( //span[@class=‘mat-option-text’] ), it prints the text of the mat-icon ( warning ) as well.

Console:

Afghanistan warning

Can anyone help how I can print Afghanistan only?

enter image description here

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Arsen
  • 65
  • 8

2 Answers2

0

You need to execute JavaScript:

WebElement span = driver.findElement(By.className("mat-option-text"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
String spanText = jse.executeScript("return arguments[0].childNodes[0].text", span);
Parolla
  • 408
  • 2
  • 6
0

The text Afghanistan is within a text node. So to retrieve the text you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.mat-option-text")))).toString());
    
  • xpath:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='mat-option-text']")))).toString());
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352