我一直在寻找替代方案,并已选择以下版本。第一个版本使用明确的等待和定义的超时时间,基于元素属性;第二个版本则基于元素失效。
首选是检查元素属性,直到达到超时时间。我已确认以下属性可证实该元素在页面上存在:
存在性 - 检查页面 DOM 中是否存在该元素的期望值。但这并不一定意味着元素可见。
//this will not wait for page to load
Assert.True(Driver.FindElement(By elementLocator).Enabled)
//this will search for the element until a timeout is reached
public static IWebElement WaitUntilElementExists(By elementLocator, int timeout = 10)
{
try
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
return wait.Until(ExpectedConditions.ElementExists(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
可见性 - 检查页面的DOM上是否存在元素并且可见的期望。可见性意味着该元素不仅被显示,而且其高度和宽度大于0。
//this will not wait for page to load
Assert.True(Driver.FindElement(By elementLocator).Displayed)
//this will search for the element until a timeout is reached
public static IWebElement WaitUntilElementVisible(By elementLocator, int timeout = 10)
{
try
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
return wait.Until(ExpectedConditions.ElementIsVisible(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found.");
throw;
}
}
可点击的 - 检查元素是否可见和启用,以便您可以单击它的期望。
//this will not wait for page to load
//both properties need to be true in order for element to be clickable
Assert.True(Driver.FindElement(By elementLocator).Enabled)
Assert.True(Driver.FindElement(By elementLocator).Displayed)
//this will search for the element until a timeout is reached
public static IWebElement WaitUntilElementClickable(By elementLocator, int timeout = 10)
{
try
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
return wait.Until(ExpectedConditions.ElementToBeClickable(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
第二选择适用于触发对象(例如菜单项)在被点击后从DOM中分离的情况下。当元素上的点击动作将触发重定向到另一个页面时,通常会出现这种情况。在这种情况下,使用检查StalenessOf(element)很有用,其中element是触发重定向到新页面的项目。
public static void ClickAndWaitForPageToLoad(By elementLocator, int timeout = 10)
{
try
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
var element = Driver.FindElement(elementLocator);
element.Click();
wait.Until(ExpectedConditions.StalenessOf(element));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}