小编典典

我如何要求Selenium-WebDriver在sendkey之后等待几秒钟?

selenium

我正在使用C#Selenium-WebDriver。发送密钥后,我要等待几秒钟。我执行以下代码以等待2秒钟。

public static void press(params string[] keys)
{
       foreach (string key in keys) 
       { 
          WebDriver.SwitchTo().ActiveElement().SendKeys(key);
          Thread.Sleep(TimeSpan.FromSeconds(2));
       }
}

我这样打电话:

press(Keys.Tab, Keys.Tab, Keys.Tab);

它工作正常。哪一个是更好的方法?


阅读 377

收藏
2020-06-26

共1个答案

小编典典

我会不惜一切代价避免使用这样的方法,因为它会减慢测试速度,但是我遇到了我没有其他选择的情况。

public void Wait(double delay, double interval)
{
    // Causes the WebDriver to wait for at least a fixed delay
    var now = DateTime.Now;
    var wait = new WebDriverWait(myWebDriver, TimeSpan.FromMilliseconds(delay));
    wait.PollingInterval = TimeSpan.FromMilliseconds(interval);
    wait.Until(wd=> (DateTime.Now - now) - TimeSpan.FromMilliseconds(delay) > TimeSpan.Zero);
}

总是最好以某种方式观察DOM,例如:

public void Wait(Func<IWebDriver, bool> condition, double delay)
{
    var ignoredExceptions = new List<Type>() { typeof(StaleElementReferenceException) };
    var wait = new WebDriverWait(myWebDriver, TimeSpan.FromMilliseconds(delay)));
    wait.IgnoreExceptionTypes(ignoredExceptions.ToArray());
    wait.Until(condition);
}

public void SelectionIsDoneDisplayingThings()
{
    Wait(driver => driver.FindElements(By.ClassName("selection")).All(x => x.Displayed), 250);
}
2020-06-26