【问题标题】:org.openqa.selenium.UnhandledAlertException: unexpected alert openorg.openqa.selenium.UnhandledAlertException:意外警报打开
【发布时间】:2015-01-02 13:34:12
【问题描述】:

我正在使用 Chrome 驱动程序并尝试测试网页。

通常它运行良好,但有时我会遇到异常:

 org.openqa.selenium.UnhandledAlertException: unexpected alert open
 (Session info: chrome=38.0.2125.111)
 (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 x86) (WARNING: The server did not  provide any stacktrace information)
 Command duration or timeout: 16 milliseconds: null
 Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
 System info: host: 'Casper-PC', ip: '10.0.0.4', os.name: 'Windows 7', os.arch: 'x86', os.version:  '6.1', java.version: '1.8.0_25'
 Driver info: org.openqa.selenium.chrome.ChromeDriver

然后我尝试处理警报:

  Alert alt = driver.switchTo().alert();
  alt.accept();

但这次我收到了:

org.openqa.selenium.NoAlertPresentException 

我附上警报的屏幕截图:

我现在不知道该怎么做。问题是我并不总是收到这个异常。当它发生时,测试失败。

【问题讨论】:

  • 这可能是根本原因吗?绕过调用 fxdriver.modals.clearFlag_ ... cf。 stackoverflow.com/questions/44568402/…
  • ChromeDriver 上的一个问题有 FirefoxDriver 解决方案,这很奇怪。这是否意味着 chrome 无法克服这种默认行为。

标签: java javascript exception selenium selenium-webdriver


【解决方案1】:

我也有这个问题。这是由于驱动程序在遇到警报时的默认行为。默认行为设置为“接受”,因此警报自动关闭,而 switchTo().alert() 找不到它。

解决办法是修改驱动的默认行为(“IGNORE”),使其不关闭alert:

DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);

那你就可以处理了:

try {
    click(myButton);
} catch (UnhandledAlertException f) {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("Alert data: " + alertText);
        alert.accept();
    } catch (NoAlertPresentException e) {
        e.printStackTrace();
    }
}

【讨论】:

  • 如果驱动程序的默认行为是接受所有警报,那么为什么它首先抛出异常?它不应该自动接受警报并继续吗?
  • 也许是为了确保开发人员知道警报正在打开?
  • 这意味着尽管进行了设置,但它没有点击警报。
  • 为什么会出现这种情况?此类警报间歇性发生的原因是什么?
【解决方案2】:

您可以使用 Selenium WebDriver 中的Wait 功能来等待警报,并在警报可用时接受它。

在 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 */ }
}

它在 Java 中的等价物 -

public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
    if (wait == null) {
        wait = new WebDriverWait(driver, 5);
    }

    try {
        Alert alert = wait.Until(new ExpectedCondition<Alert>{
            return new ExpectedCondition<Alert>() {
              @Override
              public Alert apply(WebDriver driver) {
                try {
                  return driver.switchTo().alert();
                } catch (NoAlertPresentException e) {
                  return null;
                }
              }
            }
        });
        alert.Accept();
    } catch (WebDriverTimeoutException) { /* Ignore */ }
}

它将等待 5 秒直到出现警报,如果预期的警报不可用,您可以捕获异常并处理它。

【讨论】:

    【解决方案3】:

    您是否在 try/catch 块内切换到警报?您可能还需要添加等待超时,以查看警报是否在一定延迟后显示

    try {
        // Add a wait timeout before this statement to make 
        // sure you are not checking for the alert too soon.
        Alert alt = driver.switchTo().alert();
        alt.accept();
    } catch(NoAlertPresentException noe) {
        // No alert found on page, proceed with test.
    }
    

    【讨论】:

      【解决方案4】:
      UnhandledAlertException 
      

      遇到弹出的未处理警报框时抛出。除非发现警报框场景,否则您需要将代码设置为正常运行。这克服了你的问题。

             try {
                  System.out.println("Opening page: {}");
                  driver.get({Add URL});
                  System.out.println("Wait a bit for the page to render");
                  TimeUnit.SECONDS.sleep(5);
                  System.out.println("Taking Screenshot");
                  File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                  String imageDetails = "C:\\images";
                  File screenShot = new File(imageDetails).getAbsoluteFile();
                  FileUtils.copyFile(outputFile, screenShot);
                  System.out.println("Screenshot saved: {}" + imageDetails);
              } catch (UnhandledAlertException ex) {
                  try {
                      Alert alert = driver.switchTo().alert();
                      String alertText = alert.getText();
                      System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
                      alert.accept();
                      File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                      String imageDetails = "C:\\Users";
                      File screenShot = new File(imageDetails).getAbsoluteFile();
                      FileUtils.copyFile(outputFile, screenShot);
                      System.out.println("Screenshot saved: {}" + imageDetails);
                      driver.close();
                  } catch (NoAlertPresentException e) {
                      e.printStackTrace();
                  }
              } 
      

      【讨论】:

        【解决方案5】:

        点击事件后添加下面的代码来处理

            try{
                 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
               }
         catch (org.openqa.selenium.UnhandledAlertException e) {                
                 Alert alert = driver.switchTo().alert(); 
                 String alertText = alert.getText().trim();
                 System.out.println("Alert data: "+ alertText);
                 alert.dismiss();}
        

        ...做其他事情 driver.close();

        【讨论】:

          【解决方案6】:
          DesiredCapabilities firefox = DesiredCapabilities.firefox();
          firefox.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
          

          您可以使用UnexpectedAlertBehaviour.ACCEPTUnexpectedAlertBehaviour.DISMISS

          【讨论】:

            【解决方案7】:

            我遇到了同样的问题,我做了以下更改。

            try {
                click(myButton);
            } catch (UnhandledAlertException f) {
                try {
                    Alert alert = driver.switchTo().alert();
                    String alertText = alert.getText();
                    System.out.println("Alert data: " + alertText);
                    alert.accept();
                } catch (NoAlertPresentException e) {
                    e.printStackTrace();
                }
            }
            

            效果惊人。

            【讨论】:

              【解决方案8】:

              我尝试了下面的代码,它非常适合我(Chrome)

              try{
                  System.out.println("Waiting for Alert");
                  WebDriverWait wait = new WebDriverWait(driver,10);
                  wait.until(ExpectedConditions.alertIsPresent()).dismiss();
                  System.out.println("Alert Displayed");
              }
              catch (Exception e){
                  System.out.println("Alert not Displayed");
              }
              

              【讨论】:

                【解决方案9】:

                你可以试试这个sn-p:

                public void acceptAlertIfAvailable(long timeout)
                      {
                        long waitForAlert= System.currentTimeMillis() + timeout;
                        boolean boolFound = false;
                        do
                        {
                          try
                          {
                            Alert alert = this.driver.switchTo().alert();
                            if (alert != null)
                            {
                              alert.accept();
                              boolFound = true;
                            }
                          }
                          catch (NoAlertPresentException ex) {}
                        } while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
                      }
                

                【讨论】:

                  【解决方案10】:

                  以下对我有用

                      private void acceptSecurityAlert() {
                  
                      Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)          
                                                                              .pollingEvery(3, TimeUnit.SECONDS)          
                                                                              .ignoring(NoSuchElementException.class);    
                      Alert alert = wait.until(new Function<WebDriver, Alert>() {       
                  
                          public Alert apply(WebDriver driver) {
                  
                              try {
                  
                                  return driver.switchTo().alert();
                  
                              } catch(NoAlertPresentException e) {
                  
                                  return null;
                              }
                          }  
                      });
                  
                      alert.accept();
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    以下代码将有助于处理 selenium 中的意外警报

                    try{
                    } catch (Exception e) {
                    if(e.toString().contains("org.openqa.selenium.UnhandledAlertException"))
                     {
                        Alert alert = getDriver().switchTo().alert();
                        alert.accept();
                     }
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 2017-07-22
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-10-10
                      • 2021-11-01
                      • 2022-09-29
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多