在接受警报Selenium Webdriver之前等待页面加载

时间:2016-03-07 14:41:00

标签: javascript java selenium selenium-webdriver webdriver

我正在尝试进行一些基本的网页抓取,并希望能够接受(或解除)屏幕上的任何警报,以便我可以访问页面元素。早些时候,我通过预期等待警报来管理这个。

private void handleAlert(){
    try{
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
        Logger.log("Accepting alert~!~~~~!!!");
        }catch(NoAlertPresentException e){
            // Do nothing :D
        }catch(UnhandledAlertException e){
                Logger.writeError("An alert was not handled!");
        }catch(TimeoutException e){
            Logger.writeError("There was a timeout occurring handling alert");
        }
    }
}

但是,如果页面在前2秒内未加载但随后加载(我的页面加载超时为15秒),则会出现此问题。在这种情况下,会有一个提示,但我将不再尝试解雇/接受此提示。

为了解决这个问题,我决定编写一些代码来等待页面加载,然后再尝试处理警报。代码如下:

    /**
     * Load an Url in the chrome browser via Selenium driver
     * @param url: The web address to be crawled
     * @throws InterruptedException
     */
    public boolean loadUrl(String url) throws InterruptedException{
        try{
            driver.get(url);
            waitTillPageLoads();
            handleAlert();
            return true;
        }catch(TimeoutException e){
            //e.printStackTrace();
            Logger.writeError("There was a timeout for the url: "+url);
            return false;
        }
    } 

    /**
     * Use webdriver expected conditions override to wait until
     * DOM state is completed
     */
    private void waitTillPageLoads(){
        ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() 
            {
                public Boolean apply(WebDriver driver)
                {
                    return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
                }
            };
        Wait<WebDriver> wait = new WebDriverWait(driver,30);
        wait.until(expectation);
    }

Buuuuut,如果我这样做,我得到一个AlertNotHandledException,由下面的汇总堆栈跟踪指定:

Exception in thread "main" org.openqa.selenium.UnhandledAlertException: unexpected alert open
    Session ID: 876c48f2d94d10fe30984ab94f32884e
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:164)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:577)
        at src.com.chrome.TestChromeDriver$1.apply(TestChromeDriver.java:349)
        at src.com.chrome.TestChromeDriver$1.apply(TestChromeDriver.java:1)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:238)
        at src.com.chrome.TestChromeDriver.waitTillPageLoads(TestChromeDriver.java:353)
        at src.com.chrome.TestChromeDriver.loadUrl(TestChromeDriver.java:364)
        at src.com.chrome.TestChromeDriver.crawl(TestChromeDriver.java:308)
        at src.com.chrome.TestChromeDriver.main(TestChromeDriver.java:132)

那么,我如何等待页面加载,然后尝试处理javascript警报(如果存在)。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您知道自己在做什么,并且真的必须绕过所有JavaScript警报和对话而不管后果如何,您可以随时follow this advice

((JavascriptExecutor) driver).executeScript("window.alert = function() {}; window.prompt = function() {return null}; window.confirm = function() {return true}");

你需要在每个页面加载后运行它,但它肯定比试图处理不可预测的变量行为更清晰。

(如果您想试用它,请打开浏览器的开发人员工具,将scriptlet粘贴到JS控制台,然后验证alert('hi');什么都不做。)