org.openqa.selenium.UnhandledAlertException: unexpected alert open

后端 未结 10 757
情歌与酒
情歌与酒 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:36

    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.

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

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

提交回复
热议问题