Search code examples
javaselenium-webdriverselenium-chromedrivernosuchelementexceptionfluentwait

Handle the NoSuchElementException in Fluent Wait


I know that in terms of waiting for web element that isn't in the DOM yet, the most efficient is a fluent wait. So my question is:

Is there a way to handle and catch the NoSuchElementException or any exception that fluent wait might throw because the element is not existing?

I need to have a boolean method wherein it will give me result whether the element is found or not.

This method is quite popular on the web.

public void waitForElement(WebDriver driver, final By locator){
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(60, TimeUnit.SECONDS)
            .pollingEvery(2, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

   wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });
}

What I need is, **.ignoring(NoSuchElementException.class);** will not be ignored. And once the exception is caught, it will return FALSE. On the other hand, when an element is found, it will return TRUE.


Solution

  • As an alternative as you have wanted to see the implementation of WebDriverWait with polling, here are the constructor details :

    • WebDriverWait(WebDriver driver, long timeOutInSeconds): Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others.

      WebDriverWait wait1 = new WebDriverWait(driver, 10);
      
    • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis): Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others.

      WebDriverWait wait2 = new WebDriverWait(driver, 10, 500);
      

    Update :

    To answer to your comment, you need to define the WebDriverWait instance here. Next we have to implement the WebDriverWait instance i.e. wait1 / wait2 within your code through proper ExpectedConditions clauses.