【发布时间】:2021-02-22 01:16:30
【问题描述】:
我有一个相对简单的方法来等待一个元素存在并显示出来。该方法处理给定 By 返回多个元素的情况(通常我们只希望显示其中一个,但无论如何该方法将返回找到的第一个显示元素)。
我遇到的问题是,当页面上(根本)没有匹配元素时,它所花费的时间比指定的 TimeSpan 还要多*,我不知道为什么。
*我刚刚测试了 30s 的超时时间,花了 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() 中内置的继承等待混合有关。
想听听你们对这个难题的看法。
干杯!
【问题讨论】:
标签: c# selenium-webdriver nunit parallel-testing spinwait