Handling Element Not Found Exception in Selenium WebDriver

Handling Element Not Found Exception in Selenium WebDriver

3 July 2024 Stephan Petzl Leave a comment QA

When automating mobile applications using Selenium WebDriver and Appium, it is common to encounter scenarios where an element may not be present on the page. This can lead to exceptions that halt the execution of your test scripts. In this article, we will explore effective strategies to handle such situations gracefully, ensuring that your tests continue to run smoothly.

Using findElements Instead of findElement

One approach to handle the absence of an element is to use the findElements method instead of findElement. The findElements method returns an empty list if no matching elements are found, avoiding exceptions. Here is a simple way to check if an element is present:

Boolean isPresent = driver.findElements(By.id("yourLocator")).size() > 0;

This will return true if at least one element is found and false if no elements are present.

Using Try/Catch Block

Another method to handle the absence of an element is by using a try/catch block. This allows you to catch the exception and proceed with alternative steps. Below is an example:

try {
    driver.findElement(By.cssSelector("selector"));
} catch (NoSuchElementException e) {
    System.out.println("Element does not exist!");
}

This approach ensures that your test script continues to execute even if the element is not found.

Implementing Custom Waits with Messages

If you need more control over the waiting mechanism, you can implement custom waits with error messages. This method involves creating a support class for handling WebDriver waits with custom messages:

protected void checkElementPresence(final WebDriver driver, final By by, final String errorMsg) {
    new WebDriverWaitWithMessage(driver, 10).failWith(errorMsg).until(new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver webDriver) {
            try {
                return driver.findElement(by).isDisplayed();
            } catch (NoSuchElementException | StaleElementReferenceException ignored) {
                return false;
            }
        }
    });
}

protected static class WebDriverWaitWithMessage extends WebDriverWait {
    private String message;

    public WebDriverWaitWithMessage(WebDriver driver, long timeOutInSeconds) {
        super(driver, timeOutInSeconds);
    }

    public WebDriverWait failWith(String message) {
        if (message == null || message.isEmpty()) {
            throw new IllegalArgumentException("Error message must not be null nor empty");
        }
        this.message = message;
        return this;
    }

    @Override
    public <V> V until(Function<? super WebDriver, V> isTrue) {
        if (message == null) {
            return super.until(isTrue);
        } else {
            try {
                return super.until(isTrue);
            } catch (TimeoutException e) {
                throw new TimeoutException(message, e);
            }
        }
    }
}

Conclusion

Handling the absence of elements in Selenium WebDriver can be approached in various ways, from using findElements to implementing custom waits and try/catch blocks. By applying these techniques, you can ensure that your automated tests run smoothly and efficiently.

For users looking to streamline their mobile application testing, consider using Repeato, a no-code test automation tool for iOS and Android. Repeato leverages computer vision and AI to create, run, and maintain automated tests quickly and efficiently. It simplifies the setup process and enhances the overall quality assurance experience. Learn more about Repeato here.

Like this article? there’s more where that came from!