Selenium Web-Driver Firefox配置文件 - 禁用弹出窗口和警报窗口

时间:2014-01-07 14:53:05

标签: java python selenium selenium-webdriver

我遇到某些网站的问题,导致我的浏览器在尝试切换到其他网址时出现提示,甚至关闭浏览器。一些例子:

为了使用Selenium解决警报问题,我需要切换到该警报,然后有时接受它并有时拒绝它(取决于警报的内容)。

我希望避免以这种方式解决这个问题,因为:

  1. 我需要猜测是否应该接受提醒或拒绝提醒。

  2. 切换到警报有时会引发异常,即使警告也存在。

  3. 我需要在Firefox配置文件中设置哪些首选项,以防止浏览器发出此类警报(或任何其他警报)?

    Java或Python中的答案将受到高度赞赏。

    由于

4 个答案:

答案 0 :(得分:6)

据我所知,您只能全局禁用该行为。 有一个名为 dom.disable_beforeunload 的偏好设置。您应该将其值更改为true。使用Selenium,您可以创建新的自定义Firefox配置文件:

FirefoxProfile customProfile = new FirefoxProfile();
customProfile.setPreference("dom.disable_beforeunload", true);
FirefoxDriver driver = new FirefoxDriver(customProfile);

答案 1 :(得分:1)

据我所知,不可能禁用警报等本机浏览器事件,因此您只需更好地处理它们。

1)您应该能够使用alert.getText()做出是否接受或解除警报的明智决定。

try { 
     WebDriverWait wait = new WebDriverWait(driver, 2); 
     wait.until(ExpectedConditions.alertIsPresent());
     Alert alert = driver.switchTo().alert();
     if ( alert.getText().contains("Are you sure you want to leave this page?")) {
         alert.accept();
     }
     else if ( alert.getText().contains("Some other text which means you need to dismiss")) {
         alert.dismiss();
     }
     else {
         //something else
     }
}
catch (Exception e) {

}

2)使用WebDriverWait来避免竞争条件。见上文

答案 2 :(得分:0)

我不认为Firefox配置文件会禁用这些特定元素,但您可以对某些静态逻辑行进行硬编码,这些逻辑在整个测试用例/项目中保持一致。

与主页上的点击一样,会自动关闭groovehark.com上的弹出框/警告信息

    @Test
  public void testUntitled() throws Exception {
    driver.get(baseUrl + "/#!/genre/Rap/1748"); //complete URL becomes http://grooveshark.com/#!/genre/Rap/1748
    driver.findElement(By.linkText("more…")).click(); // clicks a hyper-link which opens up that frame/pop-up
    driver.findElement(By.id("lightbox-outer")).click(); // clicks outside the opened-up frame, or simply clicks on the main page in background
  }

lightbox-outer 是主页。

答案 3 :(得分:0)

您无法禁用弹出窗口(警报),只需执行alert.accept()表示单击警告模式的ok按钮或alert.dismiss()表示单击取消或关闭按钮。

在这种情况下最糟糕的是,如果您不确定是否存在警报,则需要等待一段时间。

如果由于事件成功而出现警报(就像点击按钮一样,网页要求您确认),您不需要等待<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorControlActivated">@color/appcolor</item> <item name="colorControlHighlight">@color/appcolor</item> </style>  您可以通过转到下一步来节省时间,即将驾驶员切换到警报状态。即

wait.until(ExpectedConditions.alertIsPresent());

只是为了确保您可以使用较短的等待时间,但是,这取决于加载网页以加载网页加载网页时出现警报的情况。

相关问题