Selenium Webdriver明确等待警报引发UnhandledAlertException [英] Selenium webdriver explicit wait for alert throws UnhandledAlertException
问题描述
我必须明确等待20秒才能收到警报。如果20秒后没有警报,我应该抛出异常。以下是我的警报等待,但它在20秒前引发了未处理的警报异常。有人可以帮我吗?
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) {
}
推荐答案
如何编写自己的 ExpectedConditions
类?
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;
}
}
};
}
}
用法:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(MyExpectedConditions.waitForAlert());
说明:
WebDriverWait会在20秒内触发警报。如果不存在警报,则抛出 Exception
异常。如果 driver
成功切换到 alert
,它将返回到 defaultContent
并继续执行您的代码。
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.
这篇关于Selenium Webdriver明确等待警报引发UnhandledAlertException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!