1、使用Until和匿名函数的方法
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));
var element = wait.Until(() =>
{
var e = Driver.FindElement(By.Id("content-section"));
if(e.Displayed)
return e;
});
2、添加扩展方法WaitUntilVisible来判断
public static IWebElement WaitUntilVisible(
this IWebDriver driver,
By itemSpecifier,
int secondsTimeout = 10)
{
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, secondsTimeout));
var element = wait.Until<IWebElement>(driver =>
{
try
{
var elementToBeDisplayed = driver.FindElement(itemSpecifier);
if(elementToBeDisplayed.Displayed)
{
return elementToBeDisplayed;
}
return null;
}
catch (StaleElementReferenceException)
{
return null;
}
catch (NoSuchElementException)
{
return null;
}
});
return element;
}
调用扩展方法:
ChromeDriver driver = new ChromeDriver(); //...省略逻辑代码 element = driver.WaitUntilVisible(By.XPath("//input[@value='Save']"));
3、通过DotNetSeleniumExtras.WaitHelpers判断
1) Nuget安装引用DotNetSeleniumExtras.WaitHelpers
使用nuget搜索DotNetSeleniumExtras.WaitHelpers
,并且导入命名空间。
相关文档:VS(Visual Studio)中Nuget的使用
或者
Install-Package DotNetSeleniumExtras.WaitHelpers
2) 判断是否显示的代码
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("content-section")));
相关文档:
.NET Core(C#) 操作selenium(Chrome)对网页截完整页面长图的方法及示例代码
.NET selenium WebDriver操作调用浏览器后台执行Js(JavaScript)代码