selenium-chromedriver - 何时检查意外警报?
问题描述
我正在使用 Chromedriver、Selenium 和 Java 编写自动化程序。一步调用一种方法,该方法执行类似的操作
save.click()
单击保存按钮。有时这只是保存,有时它会引起警报(比如请填写日期字段或你有什么)。
所以我有类似的代码
page.save(); // which calls the above method
String alertMsg = waitForAlertTextAndClose(30);
(正如它所说,waitForAlertMessageAndClose() 基本上会等待警报并关闭。如果您想查看它,我将在下面更远地发布代码。
有时在单击保存后,进入下一步会导致 StaleElementReferenceException,因为页面尚未从保存完成加载。
所以我添加了这个 (waitForStaleElement() 只是等待一个陈旧的元素并设置一个 AssertionError 如果该元素没有陈旧并且 waitForXPathVisibility() 等待 xpath 或抛出一个断言。在这种情况下,我不在乎它是否没有不会过时,因为有时它不会。
我修改了保存:
try {
save.click();
waitForStaleElement("Save to go stale", save);
waitForXpathVisibility("SAVE button", saveXPath);
} catch (AssertionError ex) {
; // this is OK because sometimes it won't go stale
}
麻烦的是,现在当有一个警报时,它会在方法中抛出一个 UnexpectedAlertOpenError 并且永远不会传播回调用者。
所以我只是好奇。Chromedriver 在哪些点(或执行)会抛出 UnexpectedAlertOpenError?在我添加等待之前它没有这样做。
--- waitForAlertTextAndClose:
public String waitForAlertTextAndClose(int timeOutInSeconds) {
String alertMessage = null;
Alert element = null;
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
try {
element = wait.until(ExpectedConditions.alertIsPresent());
alertMessage = element.getText();
element.accept();
} catch (TimeoutException e) {
throw new AssertionError("Alert not present after " + timeOutInSeconds + " seconds.");
}
return alertMessage;
}
解决方案
public static void AcceptAlert(IWebDriver driver, WebDriverWait wait)
{
IAlert alert = wait.Until<IAlert>(alrt => WaitForAlert(driver));
driver.SwitchTo().Alert().Accept();
}
public static IAlert WaitForAlert(IWebDriver driver)
{
try
{
return driver.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
}
如上所述,您可以简单地单独尝试警报并在 AcceptAlert() 函数中获取警报文本。希望这对你有用!
推荐阅读
- flutter - 颤振:打开虚拟键盘时如何处理手机上的向下箭头?
- javascript - 在显示数据之前等待请求完成 - Alpine.js
- latex - 打印参考书目:空参考书目
- javascript - 需要时禁用 addEventListener 函数
- c - 使用 Linux 标头的 VSCode for Windows 中的错误
- python - 如何创建分组和堆叠的条形图
- wordpress - tailwind.config.js 清除选项无法识别 PHP 文件并导致无限重新编译
- javascript - Android[Kotlin] - 错误类型错误:["Android"].showToast 不是函数
- url - 如何在 URL 中保留“+”?
- sorting - 谷歌表格:行被脚本自动移动后重新排序范围