0

I am trying to identify a specific element and perform some actions. This specific element is not available in every element I am looping.

Below is the element I'm trying to catch.

<span class="discount-text">0% OFF</span>

I am using isDisplayed() to check if above element is present. But isDisplayed() returns true even though its not actually displayed in the view. above element is display as below when it is not displayed in the view.

<span class="discount-text">&nbsp;</span>

Is there are a way to identify this span element actually is displayed?

I have tried to get it using text as below. but getText() returns an empty string.

discountText.getText().contains("%")

Please advice me on this.

2

5 Answers 5

0

As per the software testing solutions we tends to encounter these sort of issues and for solution we are following the below mentioned approach.

<span class="discount-text">OFF</span>

So, If we see in the above Web element, we have a value as 'OFF' text. So we can create a locator which determines the visibility of the 'OFF' text.

ele = driver.findElement(By.xpath("//span[contains(text(),'OFF')]")).getText();

if ele.isequals('OFF'){
  print("Element is not displayed")
}
else{
"you can perform action then." 
}

Happy to help you.

Thanks.

0

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">&nbsp;</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();
        }
    }
}
0

There are multiple workarounds to handle such scenarios while doing web automation using Selenium. While working in outsourced software testing company and developing frameworks in multiple languages below are top 02 approaches widely used -

Method 1) Size : Fetch the text and validate if length of string is greater than zero.

Syntax - String str = driver.findElement(By.xpath("//span[@class= 'discount-text']")).getText();

if(str.length > 0){ Perform Required Actions }

Method 2) Validate Text : Fetch the text and assert with your required string.

Syntax - String str = driver.findElement(By.xpath("//span[@class= 'discount-text']")).getText();

if(str.equals("0% OFF")){ Perform Required Actions }

0

2 Things that have solved similar automation issues for me

  1. The element you are looking for could already exist on the page but the page might not actually be fully done loading. Meaning the element itself is 'visible' on the page to a program that checks based on code, but not visible to us humans that check the actual page. The solution here would be to figure out some kind of wait function (ideally not a static wait..) that allows for enough time for this page to load.
  2. The other problem I have encountered before is 'isDisplayed' just not being as stable or trustworthy as it should be. The function that has worked better for me in the past (by now over a year ago though..) is check for the element to be clickable: ...elementToBeClickable(yourElement).

Often times when I did automation I would have to use a combination of these 2 to figure out when the page was done loading (enough) for a given element to be actually visible. Keep in mind that an element being clickable doesn't mean it has to be a button or such, anything is clickable so long as it's actually visible on the screen (so text, an image, ...)

An example of this would be:

WebDriverWait WaitForElement = new WebDriverWait(driver, 10);
WaitForElement.until(ExpectedConditions.elementToBeClickable((WebElement) driver.findElement(By.cssSelector("Locate your element uniquely here"))));
-1

We can check if an element exists with Selenium webdriver. There are multiple ways to check it. We shall use the explicit wait concept in synchronization to verify the visibility of an element.

  1. Selenium can identify the presence or visibility of the elements as soon as they are present or visible in the HTML DOM. From user perspective, we can invoke isCurrentlyVisible(), isPresent() or isVisible() method on an WebElement to examine if the intended WebElement is available or not.

    if(element.isCurrentlyVisible()){ return true; } else { return false; }

  2. We can also confirm if an element is visible with the help of isDisplayed() method. This method returns a true or a false value. In case the element is invisible, the method returns a false value.

    if(element.isDisplayed()){ return true; } else { return false; }

  3. As per current implementation, Selenium may not be distinguishing between loaded and rendered elements. The ElementToBeClickable method in ExpectedConditions class sets an expectation for checking if an element is visible and enabled so that we can click it.

  4. When the element is loaded in the DOM but UI shows loading in progress we still have to wait for the JavaScript and AJAX Calls to complete loading the page, so all the WebElements on the page becomes interactable.

  5. At most to wait for complete load, we can set the pageLoadStrategy to normal but may still have to induce WebDriverWait for the intended WebElement to become present, visible, interactable or clickable.

  6. We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class.

  7. We can introduce a try/catch block. In the catch block, we shall throw the NoSuchElementException in case the element is not visible on the page.

When Page Loading takes too much time and we need to stop downloading additional subresources (images, css, js etc), Using automation strategy, we can change the pageLoadStrategy through the webdriver. If the UI is not loaded Selenium may not be able to interact with a few of the DOM elements. Using automation strategy, we can implement waits to load page or elements to be visible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.