using System;
using OpenQA.Selenium;
namespace MyApplication.Selenium.Tests.Source
{
public sealed class MyExpectedConditions
{
private void ExpectedConditions()
{
}
public static Func<IWebDriver, IAlert> AlertIsPresent()
{
return (driver) =>
{
try
{
return driver.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
};
}
}
}
你可以这样使用它:
new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) { Message = "Waiting for alert to appear" }.Until(d => MyExpectedConditions.AlertIsPresent());
Driver.SwitchTo().Alert().Accept();
请您参考如下方法:
WebDriverWait 如果在要求的等待时间内没有找到警报,将抛出一个 WebDriverTimeoutException 异常。
在 WebDriverWait 周围使用 try catch block 来捕获 WebDriverTimeoutException。
我使用如下扩展方法:
public static IAlert WaitGetAlert(this IWebDriver driver, int waitTimeInSeconds = 5)
{
IAlert alert = null;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitTimeInSeconds));
try
{
alert = wait.Until(d =>
{
try
{
// Attempt to switch to an alert
return driver.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
// Alert not present yet
return null;
}
});
}
catch (WebDriverTimeoutException) { alert = null; }
return alert;
}
并像这样使用它:
var alert = this.Driver.WaitGetAlert();
if (alert != null)
{
alert.Accept();
}
