我在某些网站上遇到了问题,导致我的浏览器在我尝试切换到其他 URL 甚至关闭浏览器时提示警报。一些例子:
-
http://grooveshark.com/
-
http://www.dollardays.com/
为了使用 Selenium 解决警报,我需要切换到该警报,然后有时接受它,有时拒绝它(取决于警报的内容)。
我希望避免以这种方式解决此问题,因为:
-
我需要猜测是应该接受警报还是拒绝警报。
-
切换到警报有时会引发异常,即使警报存在也是如此。
我需要在 Firefox-Profile 中设置什么首选项,以防止浏览器发出此类警报(或任何其他警报)?
Java或Python的答案将不胜感激。
谢谢
据我所知,您只能在全局禁用该行为。有一种偏好叫做dom.disable_beforeunload。应将其值更改为 true。使用Selenium,您可以创建一个新的自定义Firefox配置文件:
FirefoxProfile customProfile = new FirefoxProfile();
customProfile.setPreference("dom.disable_beforeunload", true);
FirefoxDriver driver = new FirefoxDriver(customProfile);
据我所知,不可能禁用警报等本机浏览器事件,因此您只需要更好地处理它们。
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 来避免竞争条件。见上文
我不认为 Firefox 配置文件会禁用此类特定元素,但您可以硬编码一些静态逻辑行,这些逻辑在测试用例/项目中保持一致。
喜欢单击主页会自动关闭 grooveshark.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
}
灯箱外是主页。
你不能禁用弹出窗口(alert),只需做 alert.accept() 意味着单击警报模式的确定按钮或 alert.dismiss() 意味着单击取消或关闭按钮。
在这种情况下,最糟糕的是,如果您不太确定警报是否存在,则需要等待一定时间。
如果由于事件成功而存在警报(就像按按钮一样,网页要求您确认),则无需等待wait.until(ExpectedConditions.alertIsPresent());
您可以通过转到下一步来节省时间,即将 DRVER 切换到警报。即
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
}
}
只是为了确保您可以使用一小段等待时间,但是是的,这取决于加载网页时存在警报的情况下加载网页的网络速度。