本文介绍了如何在C#中实现ExpectedConditions.AlertIsPresent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
will throw a WebDriverTimeoutException
exception if alert is not found in the required wait period.
在WebDriverWait
周围使用try catch块来捕获WebDriverTimeoutException
.
Use a try catch block around WebDriverWait
to catch 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();
}
这篇关于如何在C#中实现ExpectedConditions.AlertIsPresent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!