如何使用WebDriver检查是否存在警报?

Yun*_* Gu 67 selenium alert webdriver

我需要检查WebDriver中是否存在Alert.

有时它会弹出警报,但有时它不会弹出.我需要先检查警报是否存在,然后我可以接受或解除它,或者它会说:没有找到警报.

Man*_*yas 80

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()
Run Code Online (Sandbox Code Playgroud)

点击此链接https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY

  • `ExpectedConditions.alertIsPresent()`给你完全相同的东西,但是以更好的方式,只有一行:) (4认同)
  • 下面稍微错误的答案和http://stackoverflow.com/questions/8244723/alert-handling-in-selenium-2-webdriver-with-java上的答案是一个更好的方法.try/catch模型,以及笨重,记录有关没有警报的消息. (3认同)
  • 在链接中,您可以看到hos接受或关闭警报窗口 (2认同)

Lee*_*sen 23

以下(C#实现,但在Java中类似)允许您确定是否存在没有异常的警报且不创建WebDriverWait对象.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}
Run Code Online (Sandbox Code Playgroud)


nil*_*esh 11

我建议使用ExpectedConditionsalertIsPresent().ExpectedConditions是一个包装类,它实现了ExpectedCondition接口中定义的有用条件.

WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
    System.out.println("alert was not present");
else
    System.out.println("alert was present");
Run Code Online (Sandbox Code Playgroud)


and*_*dyf 7

我发现捕捉异常driver.switchTo().alert();是如此之慢Firefox(FF V20和selenium-java-2.32.0).`

所以我选择另一种方式:

    private static boolean isDialogPresent(WebDriver driver) {
        try {
            driver.getTitle();
            return false;
        } catch (UnhandledAlertException e) {
            // Modal dialog showed
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当大多数测试用例都没有对话框时,这是一种更好的方法(抛出异常很昂贵).


Vin*_*ren 5

我建议使用ExpectedConditionsalertIsPresent().ExpectedConditions是一个包装类,它实现了ExpectedCondition接口中定义的有用条件.

public boolean isAlertPresent(){
    boolean foundAlert = false;
    WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        foundAlert = true;
    } catch (TimeoutException eTO) {
        foundAlert = false;
    }
    return foundAlert;
}
Run Code Online (Sandbox Code Playgroud)

注意:这是基于nilesh的答案,但适用于捕获wait.until()方法抛出的TimeoutException.