使用Java在Selenium WebDriver(selenium 2)中进行警报处理我想检测是否弹出警报。目前我使用以下代码: try {
Alert alert = webDriver.switchTo().alert();
// check if alert exists
// TODO find better way
alert.getText();
// alert handling
log().info("Alert detected: {}" + alert.getText());
alert.accept();
} catch (Exception e) {
}问题是如果网页的当前状态没有警报,它会等待一段特定的时间,直到达到超时,然后抛出异常,因此性能非常糟糕。有没有更好的方法,也许是一个警报事件处理程序,我可以用它来动态发生警报?
3 回答

慕婉清6462132
TA贡献1804条经验 获得超2个赞
这对我来说很有用,使用显式等待WebDriver:高级用法
public void checkAlert() { try { WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); alert.accept(); } catch (Exception e) { //exception handling }}

神不在的星期二
TA贡献1963条经验 获得超6个赞
写下面的方法:
public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } // try catch (Exception e) { return false; } // catch}
现在,您可以使用上面所述的方法检查警报是否存在,如下所示:
if (isAlertPresent()) { driver.switchTo().alert(); driver.switchTo().alert().accept(); driver.switchTo().defaultContent();}

小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
警报警报= driver.switchTo()。alert();alert.accept();
您也可以拒绝警告框:
警报警报= driver.switchTo()。alert();警报()驳回();
添加回答
举报
0/150
提交
取消