Using WebDriverWait to only check till timeout, without exception

119 Views Asked by At

I am trying to use WebDriverWait for condition to be true. If it's not true after timeout, continue - instead of timeout exception.

new WebDriverWait(driver, 10)
    .pollingEvery(Duration.ofSeconds(1))
    .until(wd -> isElementPresent());

return isElementPresent()

Basically, this element can show up after few seconds delay, and not guaranteed to be there.

  • If element is becomes present, return true immediately
  • If element is not present, wait up-to 10 seconds, and return false

Can I achieve this with WebDriverWait?

1

There are 1 best solutions below

0
kenneth On

Have you tried using the .ignoring method?

new WebDriverWait(driver, 10)
    .pollingEvery(Duration.ofSeconds(1))
    .ignoring(TimeoutException.class)
    .until(wd -> isElementPresent());

return isElementPresent()

Otherwise you should try the try-catch method, which allows for more flexibility:

try {
    WebDriverWait wait = new WebDriverWait(driver, 10); // Wait for up to 10 seconds
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("yourElementId")));
    
    // Perform actions on the element
} catch (TimeoutException e) {
    // Handle the TimeoutException (e.g., log an error, take a screenshot, or report the issue)
    System.out.println("TimeoutException occurred: Element was not found within the specified timeout.");
}