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

JavaSeleniumSelenium Webdriver

Java Problem Overview


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()?

Java Solutions


Solution 1 - Java

TL;DR: Always use explicit wait. Forget that implicit wait exists.


Here is a quick rundown on the differences between explicit and implicit wait:

Explicit wait:

  • documented and defined behaviour.
  • runs in the local part of selenium (in the language of your code).
  • works on any condition you can think of.
  • returns either success or timeout error.
  • can define absence of element as success condition.
  • can customize delay between retries and exceptions to ignore.

Implicit wait:

  • undocumented and practically undefined behaviour.
  • runs in the remote part of selenium (the part controlling the browser).
  • only works on find element(s) methods.
  • returns either element found or (after timeout) not found.
  • if checking for absence of element must always wait until timeout.
  • cannot be customized other than global timeout.

Code examples with explanation. First implicit wait:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

Now explicit wait:

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement myDynamicElement = wait.until(
  ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

Both code examples do the same thing. Find a certain element and give up if not found after 10 seconds. The implicit wait can do only this. It can only try to find an element with a timeout. The strength of explicit wait is that it can wait for all kinds of conditions. Also customize timeout and ignore certain exceptions.

Example of possible conditions: elementToBeClickable, numberOfElementsToBeMoreThan or invisibilityOf. Here is a list of the built in expected conditions: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

More explanations:

The implicit wait timeout has effect only on findElement* methods. If set then all findElement* will "wait" for the set time before declaring that the element cannot be found.

How a findElement* will wait is not defined. It depends on browser or operating system or version of selenium. Possible implementations are:

  • repeatedly try to find element until timeout. return as soon as element is found.
  • try to find element. wait until timeout. try again.
  • wait until timeout. try to find element.

This list is gathered from observations and reading bug reports and cursory reading of selenium source code.


My conclusion: Implicit wait is bad. The capabilities are limited. The behaviour is undocumented and implementation dependent.

Explicit wait can do everything implicit wait can and more. The only disadvantage of explicit wait is a bit more verbose code. But that verbosity makes the code explicit. And explicit is better that implicit. Right?


Further reading:

Solution 2 - Java

Have you tried fluentWait? An implementation of the Wait interface that may have its timeout and polling interval configured on the fly. Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

see this link fluent wait description

In particular I used fluent wait in this way:

public WebElement fluentWait(final By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(5, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class);

    WebElement foo = wait.until(
        new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(locator);
            }
        }
    );
    
    return foo;          
};

As you've noticed fluent wait returns found web element. So you simply pass the locator with By type and then you can perform any actions on the found web element.

fluentWait(By.id("name")).clear();

Hope this helps you)

Solution 3 - Java

Implicit wait - It's global setting applicable for all elements and if element appear before specified time than script will start executing otherwise script will throw NoSuchElementException. Best way to use in setup method. Only affect By.findelement().

Thread.sleep() - It will sleep time for script, not good way to use in script as it's sleep without condition. What if 2 seconds are not enough in 5% of the cases?

Explicit wait: Wait for specify contains/attribute change. More used when application gives AJAX call to system and gets dynamic data and render on UI. In this case WebDriverWait is suitable.

Solution 4 - Java

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.

Solution 5 - Java

ImplicitWait :

    1. Static Wait 
    2. UnConditional Wait (No conditions are given)
    3. Applicable throughout the program

> Declaring the implicit wait in java - selenium:

driver.manage().timeout().implicitWait(20, TimeUnit.Seconds());

When to use implicit Wait?

The implicit wait is not recommended to use anywhere in the Automation suite, as this is static, and we don't know when the web element will pop up in the website.

ie. Let's say you have set implicit wait of 5 sec, and the driver is able to identify the web element in 2 seconds, as we have applied implicit wait driver will wait for 3 more seconds (till 5 seconds). This will slow down the process of automation.

Explicit Wait:

  1. Dynamic Wait
  2. Conditional Wait.
  3. Not applicable throughout the program

> Declaring the Explicit Wait in Java Selenium.

WebDriverWait wait=new WebDriverWait(driver, 20); wait.until(somecondition);

When to use an explicit wait?

We should always use explicit wait since it is dynamic in nature.

ie. Let's say you have set explicit wait of 5 sec, and the driver is able to identify the web element in 2 seconds, as we have applied explicit wait driver will not wait for 3 more seconds (till 5 seconds). The driver will continue after 2 seconds. This will fasten up the automation process.

Solution 6 - Java

Implicit waits are used to provide a waiting time (say 30 seconds) between each consecutive test steps across the entire test script or program. Next step only executed when the 30 Seconds (or whatever time is given is elapsed) after execution of previous step

Syntax:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time which is defined, has elapsed. Implicit wait has applied between each consecutive test steps across the entire test script or programs while Explicit waits are applied for a particular instance only.

Syntax:

WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,30);

Solution 7 - Java

After looking at all the answers and comments here, I am summarizing them with some code to test the simultaneous use of both implicit and explicit waits.

  • Use implicit waits only when you (generally) don't need to check for absence of elements, for example in a throw away web scraping project.

  • Never mix implicit and explicit waits together. Refer link1 and link2. If you test for absence of an element, then wait time becomes unpredictable. In the below code, only sometimes the wait time = implicit wait. You can test for absence by simply using an invalid locator.

I have taken the code in link2 and refactored it make it short and provide a summary. The code shows the actual wait time when both implicit and explicit waits are used.

The code below goes to a website and tries to find a valid element and invalid element. It uses both implicit and explicit waits. In case of invalid element search, it tries different combinations of implicit/IW and explicit/EW wait times - IW = EW, IW > EW and IW < EW.

First, the output :

WHEN ELEMENT IS FOUND WITHOUT ANY DELAY :
>>> WITH implicit = 30, explicit = 20  :::::  Wait time = 0


WHEN ELEMENT IS NOT FOUND :
a. When implicit wait = explicit wait.
>>> WITH implicit = 10, explicit = 10  :::::  Wait time = 10. ***WITH EXCEPTION*** : NoSuchElementException

b. When implicit wait > explicit wait.
>>> WITH implicit = 30, explicit = 10  :::::  Wait time = 30. ***WITH EXCEPTION*** : NoSuchElementException

c. When implicit wait < explicit wait.
>>> WITH implicit = 10, explicit = 30  :::::  Wait time = 10. ***WITH EXCEPTION*** : NoSuchElementException

The code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/*
 * Facing this chromedriver error after opening browser - [SEVERE]: Timed out receiving message
 * from renderer: 0.100.
 * */
public class TimeTest {
    static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
    static final String URL = "https://www.redbus.in/";
    static final String TIME_ZONE_NAME = "Europe/Madrid";
    static final By validLoc = By.id("src");
    static final By inValidLoc = By.id("invalid locator");
    static WebDriver driver;

        public static void main(String[] args) {
            dateFormat.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_NAME));

            //>>> Open chrome browser
            System.setProperty("webdriver.chrome.driver", "C:/drivers/chromedriver.exe");
            TimeTest.driver= new ChromeDriver();
            driver.manage().window().maximize();

            //>>> Test waiting logic.

            System.out.println("\n\nWHEN ELEMENT IS FOUND WITHOUT ANY DELAY : ");
            //mixing of implicit wait and explicit wait will not impact on webdriver behavior.
            testWait(30, 20, validLoc, "");

            System.out.println("\n\nWHEN ELEMENT IS NOT FOUND : ");
            //Run the method multiple times. Wait time generally = 10 seconds, but sometimes = 20 seconds.
            testWait(10, 10, inValidLoc, "a. When implicit wait = explicit wait.");

            //Wait time always = implicit wait. Generally ?
            testWait(30, 10, inValidLoc, "b. When implicit wait > explicit wait.");

            //Wait time always = implicit wait. Generally ?
            testWait(10, 30, inValidLoc, "c. When implicit wait < explicit wait.");

            //>>> Close the browser.
            driver.quit();
        }


        public static void testWait(int implicitWait, int explicitWait, By locator, String comment){
            // setting implicit time
            driver.manage().timeouts().implicitlyWait(implicitWait, TimeUnit.SECONDS);

            // Loading a URL
            driver.get(URL);

            // defining explicit wait
            WebDriverWait wait= new WebDriverWait(driver, explicitWait);
            // Locating and typing in From text box.


            Date start = new Date();
            String waitStats = comment + "\n>>> WITH implicit = " + implicitWait + ", explicit = " + explicitWait +
                    "  :::::  " ;//+ "Wait start = " + dateFormat.format(start)

            String exceptionMsg = "";

            try {
                WebElement fromTextBox = wait.until(ExpectedConditions.visibilityOf(driver.findElement(locator)));
            }catch (Exception ex){
                exceptionMsg = ". ***WITH EXCEPTION*** : " + ex.getClass().getSimpleName();
            }

            Date end = new Date();
            //waitStats += ", Wait end = " + dateFormat.format(end)
            waitStats += "Wait time = " +
                    TimeUnit.SECONDS.convert(end.getTime() - start.getTime(), TimeUnit.MILLISECONDS)
                    + exceptionMsg + "\n";

            System.out.println(waitStats);

        }

}

Solution 8 - Java

Implicit wait:

  1. Applicable to all driver.findelement commands
  2. Cares only for the presence of the element. If the element is invisible or not interactable then it won't care about that.

Explicit Wait

  1. You can check presence, visibility , interactability and many other things - dynamically wait for these

    WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(20)); wait.until(ExpectedConditions.presenceOfElementLocatedBy(By.id("xcxcxc"));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSUMView Question on Stackoverflow
Solution 1 - JavaLesmanaView Answer on Stackoverflow
Solution 2 - Javaeugene.polschikovView Answer on Stackoverflow
Solution 3 - JavaAnand SomaniView Answer on Stackoverflow
Solution 4 - JavaNashibukasanView Answer on Stackoverflow
Solution 5 - JavaKiran SkView Answer on Stackoverflow
Solution 6 - Javaiamsankalp89View Answer on Stackoverflow
Solution 7 - JavaMasterJoeView Answer on Stackoverflow
Solution 8 - JavaRahulView Answer on Stackoverflow