问题
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