WebDriver(Selenium2) 处理可能存在的JS弹出框

http://uniquepig.iteye.com/blog/1703103

在自动化测试过程中,有些情况下我们会遇到一些潜在的Javascript弹出框。(即某些条件下才会出现,不是固定出现),然后如果当这种弹出框出现,我们没有加以处理,WebDriver将无法进行下一步的操作,并且会抛出NoAlertPresentException的异常(从2.16版本开始)。所以,使用以下方法可以处理潜在的1个alert(javascript弹出框)。 

public boolean dealPotentialAlert(WebDriver driver,boolean option) {
boolean flag = false;
try {
Alert alert = driver.switchTo().alert();
if (null == alert)
throw new NoAlertPresentException();
try {
if (option) {
alert.accept();
System.out.println("Accept the alert: " + alert.getText());
} else {
alert.dismiss();
System.out.println("Dismiss the alert: " + alert.getText());
}
flag = true;
} catch (WebDriverException ex) {
if (ex.getMessage().startsWith("Could not find"))
System.out.println("There is no alert appear!");
else
throw ex;
}
} catch (NoAlertPresentException e) {
System.out.println("There is no alert appear!");
}
return flag;
}

  方法返回值为,调用出是否出现了alert。 
参数列表中第二个参数option为期望对alert的处理方式(true:ok/false:cancle) 
在selenium2.20及以上版本中,增加了alertIsPresent方法。 也可以将这个方法替换上面的内容。用于捕获alert。

原文地址:https://www.cnblogs.com/donaldlee2008/p/5481297.html