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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26772793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:15:20  来源:igfitidea点击:

org.openqa.selenium.UnhandledAlertException: unexpected alert open

javajavascriptexceptionseleniumselenium-webdriver

提问by Shantanu Nandan

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

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

Normally it runs fine, but sometimes I get exceptions:

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

 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

Then I tried to handle the alert:

然后我尝试处理警报:

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

But this time I received:

但这次我收到了:

org.openqa.selenium.NoAlertPresentException 

I am attaching the screenshots of the alert: First Alert and by using esc or enter i gets the second alertSecond Alert

我附上警报的截图: 第一个警报并通过使用 esc 或输入我得到第二个警报第二次警报

I am not able to figure out what to do now. The problem is that I do not always receive this exception. And when it occurs, the test fails.

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

采纳答案by RotS

I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it.

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

The solution is to modify the default behaviour of the driver ("IGNORE"), so that it doesn't close the alert:

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

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

Then you can handle it:

然后你可以处理它:

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

回答by shri046

Is your switch to alert within a try/catch block? You may also want to add a wait timeout to see if the alert shows up after a certain delay

您是否在 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.
}

回答by Vivek Singh

You can try this snippet:

你可以试试这个片段:

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

回答by Sudara

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

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

In C# -

在 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 -

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

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.

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

回答by Kanchari Srikanth

After click event add this below code to handle

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

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

... do other things driver.close();

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

回答by Mubashar

Following is working for me

以下对我有用

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

回答by Mubashar

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

You can use UnexpectedAlertBehaviour.ACCEPTor UnexpectedAlertBehaviour.DISMISS

您可以使用UnexpectedAlertBehaviour.ACCEPTUnexpectedAlertBehaviour.DISMISS

回答by Sobhit Sharma

I was facing the same issue and I made this below changes.

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

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

It worked amazingly.

它的效果惊人。

回答by khaleefa shaik

The below code will help to handle unexpected alerts in selenium

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

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

回答by Dulith De Costa

UnhandledAlertException 

is thrown when it encounters an unhanded alert box popping out. You need to set your code to act normally unless an alert box scenario is found. This overcomes your problem.

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

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