java - 当页面没有响应或查找元素超时时,Selenium 如何提示消息框?
问题描述
我使用的是Internet Explorer 版本 11.0.85,目前这个IE 在随机运行 selenium 时出现页面无响应或超时的问题。如何检测页面何时无响应或 selenium 在运行时超时并使用 JOptionpane 提示消息框?
我想要达到的目标
- 如果页面没有响应,它将提示消息框。
- 如果 Selenium 因为找不到需要单击的元素而超时,则会提示一个消息框。
我已经测试了许多可能性,例如Get 属性、try catch、Timeouts().SetScriptTimeoutSince。但是我没有人让我达到我想要的结果,我写错了还是写错了很难说,因为我需要继续运行直到它卡住才能看到结果。任何尝试过这个并拥有处理这两种情况的代码的人都非常感谢您的帮助,谢谢!
更新
我已经尝试过这段代码,它似乎可以正常工作,并且在 pburgr 示例之后可以预期,但是我不能在代码中放置超过 1 个异常,知道为什么它不能吗?
try {
// TimeSheet Button
waitForElementLocatedBy(driver,timesheet);
driver.findElement(timesheet).sendKeys(Keys.ENTER);
} catch (TimeoutException e) {
// TODO: handle exception
messageBox("Error Occur");
}
public static void messageBox(String message) {
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, message,"Information", JOptionPane.INFORMATION_MESSAGE);
}
public static void waitForElementLocatedBy(WebDriver driver, By locator) {
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(locator));
}
解决方案
Try - catch 等待 ExpectedConditions 应该可以完成这项工作。
try {wait_sec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("foo")));} catch (TimeoutException | NoSuchElementException e) {msg("Problem with loading the page occured.");}
或者
try {wait_sec(driver, 5).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.id("foo"), 1));} catch (TimeoutException | NoSuchElementException e) {msg("Problem with loading the page occured.");}
或其他一些
// modified wait method
public WebDriverWait wait_sec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
// display msgbox
public void msg(String string) {
final JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
JOptionPane.showMessageDialog(dialog, string);
}
推荐阅读
- android - AirtelMoney API 与 Android 应用程序的集成
- javascript - 使用 Angular CLI 在组件之间处理数据时遇到问题
- javascript - 如何删除wordpress中的页面链接?
- c# - 从 .NET 2 转换为 .NET 3.0 后出现 InvalidOperationException
- firebase - 云函数增量计数器不读取文档
- javascript - 只有在回调/异步函数内部时,Axios 请求才会收到 CORS 错误
- matlab - 如何在MATLAB中对矩阵中每一行的列进行置换?
- javascript - 使用 pure_funcs 丑化删除 console.log.bind
- angular - Firebase - Reference.set 失败:第一个参数在属性“users.undefined.uid”中包含未定义
- qt - 从 Source 编译 Qt 5,如何更改旧项目以使用新生成的库?