How to wait for element to load in selenium webdriver?

只谈情不闲聊 提交于 2019-11-27 23:14:14

WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("locator")));

It will wait for the element to be located for a maximum of 30 seconds if the element is found before that it will execute....

I had to change some small things from @Vicky's answer but this is what I got as a method I could call.

public static void WaitForElementLoad(By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeoutInSeconds));
            wait.Until(ExpectedConditions.ElementIsVisible(by));
        }
    }

and I call it like this:

MyClass.WaitForElementLoad(By.CssSelector("div#div1 div strong a"), 10);

I used to write a function to detect an element exists every second. if find continue, otherwise threw timeout error. but in that function i still use Thread.Sleep.

Expect other good solution.

I use ExpectedCondition.visibilityOf(element) instead of thread sleeps

Implicit wait -- max waiting time to identify object, it will identify the object for every 500 ms. if it fails to identify the object with in maximum time it will throw nosuchelement exception.

Explicit wait -- used for ajax page loads for the same purpose.

maximum waiting time is same as thread.sleep

Wrote a method for a project:

public static void WaitForElementPresentBy(By by)
        {
            try
            {
                Wait.Until(ExpectedConditions.ElementIsVisible(by));
            }
            catch (TimeoutException te)
            {

                Assert.Fail("The element with selector {0} didn't appear. The exception was:\n {1}", by, te.ToString());
            }
        }

Wait should have already been defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!