如何在Selenium webdriver中等待警报?

11

可能是重复问题:
selenium 2.4.0,如何检查警报是否存在

我正在使用以下代码关闭警报窗口:

Alert alert3 = driver.switchTo().alert();
alert3.dismiss();

主窗口打开几秒钟后,警报提示框出现。

我该如何等待并检查警报框是否出现?


请参考我的答案:https://stackoverflow.com/questions/42358965/how-to-handle-authentication-alert-of-browser-in-selenium-webdriver/59611252#59611252 - Shubham Jain
2个回答

15

没有默认方法可以等待警报。

但是,你可以编写自己的方法,类似于以下内容。

waitForAlert(WebDriver driver)
{
   int i=0;
   while(i++<5)
   {
        try
        {
            Alert alert = driver.switchTo().alert();
            break;
        }
        catch(NoAlertPresentException e)
        {
          Thread.sleep(1000);
          continue;
        }
   }
}

客户不接受我们使用死等待(Thread.sleep),他根本不会接受这个PR。我们不能用预期条件来替换它吗? - paul

-1
public boolean isAlertPresent() {

  boolean presentFlag = false;

  try {

   // Check the presence of alert
   Alert alert = driver.switchTo().alert();
   // Alert present; set the flag
   presentFlag = true;
   // if present consume the alert
   alert.accept();

  } catch (NoAlertPresentException ex) {
   // Alert not present
   ex.printStackTrace();
  }

  return presentFlag;

 }

1
该方法不会等待警报。它只会检查警报是否存在。 - Santoshsarma
抱歉。是的。有点混淆了。 试试这个链接: https://dev59.com/yWsy5IYBdhLWcg3wzBF4 - eugene.polschikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接