问题
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