Python & Selenium: Difference between driver.implicitly_wait() and time.sleep()

Yes, I know both are used to wait for some specified time.

Selenium:

driver.implicitly_wait(10)

Python:

import time
time.sleep(10)

Is there any difference between these two?


Solution 1:

time.sleep(secs)

time.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

You can find a detailed discussion in How to sleep webdriver in python for milliseconds


implicitly_wait(time_to_wait)

implicitly_wait(time_to_wait) is to specify the amount of time the WebDriver instance i.e. the driver should wait when searching for an element if it is not immediately present in the HTML DOM in-terms of SECONDS when trying to find an element or elements if they are not immediately available. The default setting is 0 which means the driver when finds an instruction to find an element or elements, the search starts and results are available on immediate basis.

In this case, after a fresh loading of a webpage an element or elements may be / may not be found on an immediate search. So your Automation Script may be facing any of these exceptions:

  • NoSuchElementException
  • TimeoutException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • ElementClickInterceptedException
  • ElementNotInteractableException

Hence we introduce ImplicitWait. By introducing ImplicitWait the driver will poll the DOM Tree until the element has been found for the configured amount of time looking out for the element or elements before throwing a NoSuchElementException. By that time the element or elements for which you had been looking for may be available in the HTML DOM. As in your code you have already set ImplicitWait to a value of 10 seconds, the driver will poll the HTML DOM for 10 seconds.

You can find a detailed discussion in Using implicit wait in selenium

Solution 2:

  • time.sleep(10) pauses code execution exactly 10 seconds.
  • driver.implicitly_wait(10) waits maximum 10 seconds for element's presence. If it is found after 2 seconds then code execution will be continued without wait for more 8 seconds.