org.openqa.selenium.UnhandledAlertException:意外警报打开

时间:2014-11-06 06:07:41

标签: java javascript exception selenium selenium-webdriver

我正在使用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

我附上警报的屏幕截图 - First Alert and by using esc or enter i gets the second alert Second Alert

我现在无法弄明白该做什么。问题是我总是没有收到这个例外。当它发生时,测试失败。

11 个答案:

答案 0 :(得分:22)

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

解决方案是修改驱动程序的默认行为(“IGNORE”),以便它不会关闭警报:

Copy if newer

然后你可以处理它:

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

答案 1 :(得分: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秒直到出现警报,如果预期的警报不可用,您可以捕获异常并处理它。

答案 2 :(得分:1)

你的开关是否在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.
}

答案 3 :(得分:0)

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

C:\Program Files\Weka-3-6\weka.jar

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

答案 4 :(得分:0)

DesiredCapabilities firefox = DesiredCapabilities.firefox();
firefox.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);

您可以使用UnexpectedAlertBehaviour.ACCEPTUnexpectedAlertBehaviour.DISMISS

答案 5 :(得分:0)

我也遇到了同样的问题,我在进行以下更改。

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

效果惊人。

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

\d+

答案 9 :(得分:-1)

您可以尝试以下代码段:

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 :(得分:-1)

以下是为我工作

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