org.openqa.selenium.UnhandledAlertException: unexpected alert open

后端 未结 10 742
情歌与酒
情歌与酒 2020-11-30 06:33

I am using a Chrome Driver and trying to test a webpage.

Normally it runs fine, but sometimes I get exceptions:

 org.openqa.selenium.UnhandledAlertE         


        
10条回答
  •  自闭症患者
    2020-11-30 07:33

    You can use Wait functionality in Selenium WebDriver to wait for an alert, and accept it once it is available.

    In C# -

    public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
    {
        if (wait == null)
        {
            wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
        }
    
        try
        {
            IAlert alert = wait.Until(drv => {
                try
                {
                    return drv.SwitchTo().Alert();
                }
                catch (NoAlertPresentException)
                {
                    return null;
                }
            });
            alert.Accept();
        }
        catch (WebDriverTimeoutException) { /* Ignore */ }
    }
    

    Its equivalent in Java -

    public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
        if (wait == null) {
            wait = new WebDriverWait(driver, 5);
        }
    
        try {
            Alert alert = wait.Until(new ExpectedCondition{
                return new ExpectedCondition() {
                  @Override
                  public Alert apply(WebDriver driver) {
                    try {
                      return driver.switchTo().alert();
                    } catch (NoAlertPresentException e) {
                      return null;
                    }
                  }
                }
            });
            alert.Accept();
        } catch (WebDriverTimeoutException) { /* Ignore */ }
    }
    

    It will wait for 5 seconds until an alert is present, you can catch the exception and deal with it, if the expected alert is not available.

提交回复
热议问题