Wait vs Sleep

a question as old as time itself lmao.

How wait actually works?

When we try to find an element using driver.find_element(), underneath the hood, we are basically querying the web element from the webpage.

refer selenium architecture for more info.

This request is sent out only once. If the element is not found, we are returned with the error message No Such Element.

When we use wait (implicit or explicit), what we are essentially doing is querying the web element from the webpage until our set wait time.

Example: If we give an implicit or explicit wait of 4 seconds, we are constantly checking for the elements presence for up to 4 seconds before sending out an error message.

One important difference to take note of is that when an element is found within the wait time, we are not going to wait for the entirety of the wait time.

Example: If the wait time is 4 seconds and we found the element in 2 seconds, we are not going to wait for additional 2 seconds to complete the total 4 seconds of wait time. We would move on to the next line.

What does sleep do?

Well, using sleep is an easy way to have some delay, but is also a very inefficient way to do it.

Since wait is dynamic in nature, sleep is extremely static.

There is no way to control the flow of the program if we find an element before the given sleep time.

Example: If we use time.sleep(4), and the element has already been found, we would still have to wait for the complete 4 seconds before proceeding to the next line in the code.

Just use wait and avoid using sleep as much as you can when it comes to selenium.

It is often seen as a lack of experience when a developer starts adding a bunch of sleep statements instead of using wait.

Updated on