As per the description in your question I understand that in your web page there are several <span>
to display discount text.
From these you want to get those <span>
that actually have some text within and ignore those with just a space or are empty.
The isDisplayed()
method you have tried always returned true because the element was actually present in the page and was displaying. It's just that the element didn't have any data to show.
So rather use a different approach. In your loop get the <span>
and try to check if it contains certain expected text.
Here is what I have tried and worked:
HTML:
<html>
<head>
</head>
<body>
<span class="discount-text">0% OFF</span>
<span class="discount-text"> </span>
<span class="discount-text"></span>
<span class="discount-text">50% OFF</span>
<span class="discount-text">50% Discount</span>
</body>
</html>
JAVA Code:
public class Demo {
public static void main(String[] args) {
try {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get("file:///home/staah/eclipse-workspace/Demo/resource/index.html");
Thread.sleep(2000);
List<WebElement> discounts = driver.findElements(By.className("discount-text"));
for(WebElement discount : discounts) {
if(discount.getText().contains("%")) {
System.out.println(discount.getText() + ": pass");
} else {
System.out.println(discount.getText() + ": fail");
}
}
Thread.sleep(5000);
driver.close();
driver.quit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
size() > 0
works but there may be corner cases.