I need to check the existence of Alert in WebDriver.
Sometimes it pops up an alert but sometimes it will not pop up. I need to check if the alert exists first, then I can accept or dismiss it or it will say: no alert found.
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
检查此处的链接https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
以下(C# 实现,但在 Java 中类似)允许您确定是否存在警报而没有异常并且不创建WebDriverWait
对象。
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
我建议使用ExpectedConditions和alertIsPresent()。ExpectedConditions 是一个包装类,它实现了ExpectedCondition接口中定义的有用条件。
WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
System.out.println("alert was not present");
else
System.out.println("alert was present");
我发现在(FF V20 & selenium-java-2.32.0)中捕获异常driver.switchTo().alert();
非常慢。`Firefox
所以我选择了另一种方式:
private static boolean isDialogPresent(WebDriver driver) {
try {
driver.getTitle();
return false;
} catch (UnhandledAlertException e) {
// Modal dialog showed
return true;
}
}
当您的大多数测试用例都不存在对话框时,这是一种更好的方法(抛出异常很昂贵)。
我建议使用ExpectedConditions和alertIsPresent()。ExpectedConditions 是一个包装类,它实现了ExpectedCondition接口中定义的有用条件。
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
} catch (TimeoutException eTO) {
foundAlert = false;
}
return foundAlert;
}
注意:这是基于 nilesh 的回答,但适用于捕获由 wait.until() 方法抛出的 TimeoutException。
ExpectedConditions
已过时,因此:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
此代码将检查警报是否存在。
public static void isAlertPresent(){
try{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex){
System.out.println("Alert is NOT Displayed");
}
}
public static void handleAlert(){
if(isAlertPresent()){
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
public static boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}catch(NoAlertPresentException ex){
return false;
}
}
公共布尔 isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}