2015-04-23 64 views
4

作为Selenium的PhantomJSDriver的新手,它如何处理JS警报?如何使用WebDriver在PhantomJS中处理/接受JS Alerts?

我发现JSPhantom onAlert文档,但什么会为

Driver.SwitchTo().Alert().Accept(); 

相当于PhantomJSDriver的代码是什么?

目前,我已经提前返回了PhantomJSDriver的guard子句来阻止异常,但是应该如何与PhantomJS中的js警报交互?

+1

我不认为Ghostdriver支持警报处理。看到这个 - https://github.com/detro/ghostdriver/issues/20。看到这个问题 - http://stackoverflow.com/questions/15708518/how-can-i-handle-an-alert-with-ghostdriver-via-python – LittlePanda

回答

7

我的PhantomJS Web Driver处理警报有类似的问题。下面的代码似乎解决了这个问题。 这是一个C#实现,但应与Java工作过..

 public IAlert GetSeleniumAlert() 
 
      { 
 
       //Don't handle Alerts using .SwitchTo() for PhantomJS 
 
       if (webdriver is PhantomJSDriver) 
 
       { 
 
        var js = webdriver as IJavaScriptExecutor; 
 

 
        
 
        var result = js.ExecuteScript("window.confirm = function(){return true;}") as string; 
 
        
 
        ((PhantomJSDriver)webdriver).ExecutePhantomJS("var page = this;" + 
 
               "page.onConfirm = function(msg) {" + 
 
               "console.log('CONFIRM: ' + msg);return true;" + 
 
                "};"); 
 
        return null; 
 
       } 
 

 
       try 
 
       { 
 
        return webdriver.SwitchTo().Alert(); 
 
       } 
 
       catch (NoAlertPresentException) 
 
       { 
 
        return null; 
 
       } 
 
      }

后来在你期望的代码出现警报

IAlert potentialAlert = GetSeleniumAlert(); 
 
       if (potentialAlert != null) //will always be null for PhantomJS 
 
       { 
 
        //code to handle Alerts 
 
        IAlert alert=webDriver.SwitchTo().Alert(); 
 
        alert.Accept(); 
 
       }

对于PhantomJS,我们正在设置默认响应以警报作为接受。

3

我不认为PhantomJS目前支持警报处理。

只需接受警报(在Python/Splinter中),为每个稍后有警报的重新加载的页面尝试此操作。

driver.execute_script("window.confirm = function(){return true;}"); 

查看更多的参考文献here

相关问题