In this post, we will learn about the various wait commands available in Selenium Python using the SeleniumBase framework. Using wait commands when doing browser automation is inevitable. Therefore, it’s important to understand how to use wait commands the right way.
Using “Wait” the Wrong way
Now, this one, in particular, is a pet-peeve of mine. I have seen time and again in many codebases where hard-coded sleeps are used instead of implementing the right wait commands. I am sure you have seen this before as well or a variation of the code below –
# I have no idea why this test is failing, so I will simply throw in a random sleep here of 5 seconds. time.sleep(5)
While this one line in a single test won’t do much harm but just imagine when this becomes the “norm” for most of your tests. Soon, you will find your test run time to double, triple, or even quadruple * gulps * due to that 1 harmless line.
Using “Wait” conditionally
Now that we know using hard-coded sleep is a bad practice, what can we do when we still need to use wait in our tests? Well, you would still use wait commands but this time you will wait for a particular condition to complete.
For example, if you need to wait for an element to be visible on the screen so that you can perform your next step, you could do something like this –
# wait for loading screen to appear self.wait_for_element_visible(self.loading_overlay)
In the sample code above, I am not explicitly telling my test to wait ‘x’ amount of seconds before performing the next step. Rather, I am using a max timeout (6 seconds set in config) for my element to be visible on the screen. This way, my element can appear on the screen in 2 secs or 4 seconds, and then it will move on to the next steps saving you a couple of extra seconds!
Some other wait commands to use –
# check whether the element is not visible self.wait_for_element_not_visible(self.loading_overlay) # wait for a particular text to appear self.wait_for_text("$300.00", self.subtotal_text)
You can read about all the available wait commands in the SeleniumBase API docs here.
Check out the video below to learn more about the wait commands in Selenium Python –
To learn more about Selenium Python, check out the full tutorial series here for free!
I hope this post helped you out, let me know if you have any questions in the comments below!
Happy testing!