Selenium Webdriver明确等待警报引发UnhandledAlertException

编程入门 行业动态 更新时间:2024-10-09 15:16:56
本文介绍了Selenium Webdriver明确等待警报引发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

本文发布于:2023-11-27 16:21:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   Selenium   Webdriver   UnhandledAlertException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!