Handle the NoSuchElementException in Fluent Wait

早过忘川 提交于 2019-12-04 14:15:41

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, we have just defined the WebDriverWait instance here. Next we have to implement the WebDriverWait instance i.e. wait1/wait2 within our code through proper ExpectedCondition clauses. The JavaDocs for ExpectedCondition is here.

You can use WebDriverWait with polling and ignoring

Example:

public boolean isElementPresentWithWait(WebDriver driver, WebElement element) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.pollingEvery(3, TimeUnit.SECONDS).ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOf(element);
        return true;
    } catch (TimeoutException e) {
        return false;
    }
}

Methods ignoring and pollingEvery return instance of FluentWait<WebDriver>

Here it is:

public boolean waitForElementBoolean(WebDriver driver, By object){
    try {
        WebDriverWait wait = new WebDriverWait(driver,60);
        wait.pollingEvery(2, TimeUnit.SECONDS);
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(object));
        return true;
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
        return false;
    }
}

I integrated the fluent wait with the explicit wait. :D Thank you guys! :)

you can try with this below code snippet

    /*
 * wait until expected element is visible
 */
public boolean waitForElement(WebDriver driver, By expectedElement) {
    boolean isFound = true;
    try {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds , 300);
        wait.until(ExpectedConditions.visibilityOfElementLocated(expectedElement));
        makeWait(1);
    } catch (Exception e) {
        //System.out.println(e.getMessage());
        isFound = false;
    }
    return isFound;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!