Selenium 如何在页面无响应或查找元素超时时提示消息框?

Selenium how prompt message box when page is not responding or timeout on finding the element?

我正在使用 Internet Explorer 版本 11.0.85,目前这个 IE 在 运行随机硒。 运行ning 时如何检测页面未响应或 selenium 超时并使用 JOptionpane 提示消息框?

我想达到的目标

  1. 如果页面没有响应,它会提示消息框。
  2. 如果Selenium因为找不到需要点击的元素而超时,它会提示一个消息框。

我已经测试了很多可能性,例如 Get attribute,try catch,Timeouts().SetScriptTimeoutSince。但是我的 none 让我达到了我想要的结果,我是否写错了很难说,因为我需要保持 运行 直到它卡住才能看到结果。任何尝试过此操作并拥有处理这两种情况的代码的人都非常感谢您的帮助,谢谢!

更新

我已经尝试过这段代码,它似乎可以正常工作,并且预期会遵循 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));
   }

尝试 - 等待 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);
}