How to Wait for an Alert in Selenium WebDriver with C#?

无人久伴 提交于 2020-02-23 08:26:25

问题


How can i set Selenium WebDriver to Wait for an Alert before accepting it instead of Thread.Sleep?

As website, sometimes loads very slowly or sometimes fast.

Thanks


回答1:


You should apply webdriver wait for an alert to be present properly.

 new WebDriverWait(driver, TimeSpan.FromSeconds(15));
        wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());

OR write a boolean function to check alert present and use it for wait

bool IsAlertShown(WebDriver driver) {
  try {
    driver.SwitchTo().Alert();
  } catch(NoAlertPresentException e) {
    return false;
  }
  return true;
}

Use it as below

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(driver => IsAlertShown(driver));



回答2:


You can use 'WebDriverWait'

IWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3))
IWebElement element = wait.Until(driver => driver.FindElement(By.Name("q")));

https://selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Support_UI_WebDriverWait.htm



来源:https://stackoverflow.com/questions/60183880/how-to-wait-for-an-alert-in-selenium-webdriver-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!