单击网页上的搜索后,将弹出警报。我需要等到弹出窗口出现。我不必使用Thread.sleep。
ExpectedConditions类具有特定的等待警报弹出的窗口。
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.alertIsPresent());
您可以使用wait
命令:
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
ExpectedConditions
已过时,请尝试使用此:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
尝试此操作,缺点是此操作没有超时。必须确保将显示弹出窗口。
while (driver.WindowHandles.Count == 1)
{
//leave it blank
}
这怎么办?
public static class SeleniumExtensions
{
public static IAlert WaitAlert(this ITargetLocator locator, int seconds = 10)
{
while (true)
{
try { return locator.Alert(); }
catch (NoAlertPresentException) when (--seconds >= 0) { Thread.Sleep(1000); }
}
}
}
为我工作:
var alert = _driver.SwitchTo().WaitAlert();
有点粗鲁,但为我工作。
public IAlert WaitAlert(int timeOut)
{
for (int cont = timeOut; cont > 0; cont--)
{
try
{
return driver.SwitchTo().Alert();
}
catch (NoAlertPresentException erro)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
}
throw new NoAlertPresentException();
}