Selenium C# WebDriver: Wait until element is present

前端 未结 24 3245
礼貌的吻别
礼貌的吻别 2020-11-22 08:53

I want to make sure that an element is present before the webdriver starts doing stuff.

I\'m trying to get something like this to work:

WebDriverWait w         


        
24条回答
  •  星月不相逢
    2020-11-22 09:44

    Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls.

    Many times you'll want the FindElement to fail right away when an element is not present (you're testing for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception. The default implicit wait is set to 0 seconds.

    I've written a little extension method to IWebDriver that adds a timeout (in seconds) parameter to the FindElement() method. It's quite self-explanatory:

    public static class WebDriverExtensions
    {
        public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
                return wait.Until(drv => drv.FindElement(by));
            }
            return driver.FindElement(by);
        }
    }
    

    I didn't cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.

    Usage is straightforward:

    var driver = new FirefoxDriver();
    driver.Navigate().GoToUrl("http://localhost/mypage");
    var btn = driver.FindElement(By.CssSelector("#login_button"));
    btn.Click();
    var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
    Assert.AreEqual("Employee", employeeLabel.Text);
    driver.Close();
    

提交回复
热议问题