如何使用phantomjs无头浏览器处理selenium中的警报

问题描述 投票:3回答:1

Selenium版本:3.4.0 phantomjs版本:2.1.1 java:1.8.0_151

我尝试了下面的东西,但它对我没有用。

在此处输入代码

1:

webDriver instanceof PhantomJSDriver){
              JavascriptExecutor je = (JavascriptExecutor) driver;
              je.executeScript("window.alert = function(){};");
              je.executeScript("window.confirm = function(){return true;};");    
              System.out.println("Alert has been handled"); }
            else {
                  Alert a1 = driver.switchTo().alert();
                  a1.accept();  
              }

2:

      /*((PhantomJSDriver)driver).executeScript("window.alert = function(){}");
      ((PhantomJSDriver)driver).executeScript("window.confirm = function(){return true;}");*/

3:

      PhantomJSDriver phantom = (PhantomJSDriver) driver;
            phantom.executeScript("window.confirm = function(){return true;};");

4:

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

5 :

PhantomJSDriver phantom = (PhantomJSDriver)driver;
       phantom.executePhantomJS("var page = this;" +
               "page.onAlert = function(msg) {" +
                      "console.log('ALERT: ' + msg);" +
               "};");

       phantom.executePhantomJS("var page = this;" +
               "page.onConfirm = function(msg) {" +
                      "console.log('CONFIRM: ' + msg);"+ "return true;" +"};");

除了上面,请你建议吗?

java selenium phantomjs
1个回答
0
投票

要在PhantomJS中处理警报,您必须等待警报出现,然后将WebDriver强制转换为JavascriptExecutor。您可以使用可以使用以下代码块:

((JavascriptExecutor) driver).executeScript("window.alert = function(msg){};");
//or
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg){return true;};");
driver.findElement(By.id("element_which_trigers_the_alert")).click();
© www.soinside.com 2019 - 2024. All rights reserved.