Alex Rivera | Logout

When to use explicit wait vs implicit wait in Selenium Webdriver?

Asked 2012-05-01T20:50:33.900
64

I am using:

driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);

But it still fails continuously for the below element

    driver.findElement(By.id("name")).clear();
    driver.findElement(By.id("name")).sendKeys("Create_title_01");

I have added wait code:

for (int second = 0;; second++) {
        if (second >= 120) fail("timeout");
        try { if (isElementPresent(By.id("name"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
    }

Shouldn't implicit wait take care of waiting till an element is found? Also would it be better if I use Explicit wait instead of the code I have added that has Thread.sleep()?

Edit
Report

1 Answer

2

Have you tried using 'WebDriverWait' ? I imagine what you want is this:

WebDriverWait _wait = new WebDriverWait(driver, new TimeSpan(0, 0, 2)); //waits 2 secs max
_wait.Until(d => d.FindElement(By.Id("name")));
//do your business on the element here :)

This pretty much will, to my understanding, do what your current code is. It will constantly try the method (while ignoring not found exceptions) until the timeout of the passed in timespan is reached and a third parameter can be entered to specify the sleep in milliseconds. Sorry if this is what implicitlyWait does too!

Edit: I did some reading today and understand your question better and realise that this does exactly what your setting of implicit wait should do. Will leave it here just in case the code itself can help someone else.

answered 2012-05-01T21:56:15.077

Your Answer