Selenium C# WebDriver: Wait until element is present

前端 未结 24 3063
礼貌的吻别
礼貌的吻别 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:41

    Inspired by Loudenvier's solution, here's an extension method that works for all ISearchContext objects, not just IWebDriver, which is a specialization of the former. This method also supports waiting until the element is displayed.

    static class WebDriverExtensions
    {
        /// 
        /// Find an element, waiting until a timeout is reached if necessary.
        /// 
        /// The search context.
        /// Method to find elements.
        /// How many seconds to wait.
        /// Require the element to be displayed?
        /// The found element.
        public static IWebElement FindElement(this ISearchContext context, By by, uint timeout, bool displayed=false)
        {
            var wait = new DefaultWait(context);
            wait.Timeout = TimeSpan.FromSeconds(timeout);
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
            return wait.Until(ctx => {
                var elem = ctx.FindElement(by);
                if (displayed && !elem.Displayed)
                    return null;
    
                return elem;
            });
        }
    }
    

    Example usage:

    var driver = new FirefoxDriver();
    driver.Navigate().GoToUrl("http://localhost");
    var main = driver.FindElement(By.Id("main"));
    var btn = main.FindElement(By.Id("button"));
    btn.Click();
    var dialog = main.FindElement(By.Id("dialog"), 5, displayed: true);
    Assert.AreEqual("My Dialog", dialog.Text);
    driver.Close();
    

提交回复
热议问题