我有一个相对简单的方法来等待元素存在并显示出来。该方法可以处理为给定的By返回多个元素的情况(通常我们只希望显示其中一个,但是无论如何该方法都将返回找到的第一个显示元素)。
我遇到的问题是,当页面上根本没有匹配的元素时,它花费的时间量比指定的TimeSpan多*,我不知道为什么。
*我刚刚进行了30秒的超时测试,结果花了5m多一点
代码:
/// <summary>
/// Returns the (first) element that is displayed when multiple elements are found on page for the same by
/// </summary>
public static IWebElement FindDisplayedElement(By by,int secondsToWait = 30)
{
WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(secondsToWait);
// Wait for an element to exist and also displayed
IWebElement element = null;
bool success = spinwait.SpinUntil(() =>
{
var collection = WebDriver.FindElements(by);
if (collection.Count <= 0)
return false;
element = collection.ToList().FirstOrDefault(x => x.Displayed == true);
return element != null;
},TimeSpan.FromSeconds(secondsToWait));
if (success)
return element;
// if element still not found
throw new NoSuchElementException("Could not find visible element with by: " + by.ToString());
}
您可以用这样的名称来调用它:
[Test]
public void FindDisplayedElement()
{
webDriver.Navigate().GoToUrl("https://stackoverflow.com/questions");
var nonExistenetElementBy = By.CssSelector("#custom-header99");
FindDisplayedElement(nonExistenetElementBy,10);
}
如果您运行测试(超时时间为10秒),则会发现实际退出大约需要100秒。
看起来可能与内置在spinwait.WaitUntil()中的WebDriver.FindElements()中内置的继承等待的混合有关。
想听听你们对这个难题的看法。
干杯!