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。