Home > Software engineering >  Selenium wait.until method
Selenium wait.until method

Time:12-28

Hello fellow programmers, I have a simple question.

Is

wait = WebDriverWait(browser, 10)

equivalent to

time.sleep(10)

?

I'm developing this selenium app and sometimes the server traffic is quite massive which leads to different loading times when moving from page to page. I found time.sleep(N) isn't efficient but if I use the wait.until EC block will the code execute once the condition is met?
It won't waste time if use wait = WebDriverWait(browser, 60) and the page loads in 3 seconds?

CodePudding user response:

The hardcoded pause of time.sleep(10) and the explicit wait of wait = WebDriverWait(browser, 10) are definitely not the same.
The hardcoded pause of time.sleep(10) will pause execution of the code for the period of 10 seconds with no conditions.
The explicit wait of wait = WebDriverWait(browser, 10) will poll the web page until the specified condition is met. Once the condition is met your code will continue execution immediately.
For example if you defined your explicit wait to wait until element located by div.selected is visible, Selenium will poll the DOM every some predefined period, lets say every 100 milliseconds and when it founds such element visible the wait will finish and your code will continue execution.
In case the condition was not met up to the defined timeout, in the example above it is 10 seconds, Selenium will throw TimeoutException Exception.
There are a lot of tutorials about this, for example here

CodePudding user response:

time.sleep(10) and wait = WebDriverWait(browser, 10) both are explicit waits.

The main difference is that

time.sleep(10) is the worst kind of explicit wait.

What it means is that it will halt the program execution for the defined time period, in this case, 10 secs.

Whereas WebDriverWait will look for EC conditions every 500ms if found then return if not retry again and again until a timeout occurs and then throw

TimeOutException

which is a generic error again.

Also,

Since explicit waits allow you to wait for a condition to occur, they make a good fit for synchronising the state between the browser and its DOM, and your WebDriver script.

here is the official docs for explicit waits.

  • Related