首页 > 解决方案 > 当页面没有响应或查找元素超时时,Selenium 如何提示消息框?

问题描述

我使用的是Internet Explorer 版本 11.0.85,目前这个IE 在随机运行 selenium 时出现页面无响应或超时的问题。如何检测页面何时无响应或 selenium 在运行时超时并使用 JOptionpane 提示消息框?

我想要达到的目标

  1. 如果页面没有响应,它将提示消息框。
  2. 如果 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));
   }

标签: javaseleniumtimeout

解决方案


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);
}

推荐阅读