Selenium webdriver explicit wait for alert throws UnhandledAlertException

无人久伴 提交于 2019-12-12 01:47:48

问题


I have to wait explicitly for 20 seconds for presence of an alert. If alert is not present after 20 seconds, I should throw an exception. Following is my wait for alert, but it throws unhandled Alert Exception before 20 seconds. Can someone help me on this?

try {
    new WebDriverWait(driver, 20).ignoring(NoAlertPresentException.class)
            .ignoring(UnhandledAlertException.class) 
            .until(ExpectedConditions.alertIsPresent());

} catch (Exception e) {
}

回答1:


How about writing your own ExpectedConditions class?

public abstract class MyExpectedConditions {
public static ExpectedCondition<Boolean> waitForAlert() {
    return new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver driver) {
            try {
                driver.switchTo().alert();
                driver.switchTo().defaultContent();
                return true;
            } catch (NoAlertPresentException e) {
                return false;
            }
        }
    };
}

}

Usage:

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(MyExpectedConditions.waitForAlert());

Explanation: WebDriverWait causes switch to alert during 20 seconds. If alert is NOT present, Exception is thrown an caught. If driver successfully switches to alert, it returns to defaultContent and continues with your code.

If you want to handle this alert, you will have to switch to alert by yourself.



来源:https://stackoverflow.com/questions/42373356/selenium-webdriver-explicit-wait-for-alert-throws-unhandledalertexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!