Using Selenium Wait Commands to Improve Page Load Tutorial
Sauce AI for Test Authoring: Move from intent to execution in minutes.|xBack to ResourcesBlogPosted
Sauce AI for Test Authoring: Move from intent to execution in minutes.
|
x
Blog
Using Selenium Wait Commands to Improve Page Load Tutorial
Learn how to use Selenium & # x27; s implicit, explicit, and smooth wait commands to ameliorate automated examination playscript.
Have you ever run an machine-driven test only to have it crash on you because of a timeout or element elision such asNoSuchElementException or ElementNotVisibleException? Don & # x27; t worry: it & # x27; s not uncommon for tests to be flaky because of extraneous constituent, with the major ones being page load multiplication.
The good news is that you can keep slow-loading Page or constituent from ram your trial by habituate one ofSelenium& # x27; s three wait commands. Using these wait commands gives the DOM time to lade HTML ingredient or pages, preventing your tests from ram as easily.
In this guide you will memorize how to use Selenium & # x27; s implicit, explicit, and fluent wait bidding to improve automated test scripts.
How to Implement Wait for Page to Load with Selenium
This tutorial starts by study a few mere Selenium tests written in Python that don & # x27; t use wait commands to determine why they & # x27; re failing. Then, it considers each of the three wait commands—implicit wait, explicit postponement, and smooth-spoken wait—and how they can improve these test.
Selenium Tests without Wait Commands
Let & # x27; s look at three Selenium exam that don & # x27; t use wait commands and regard why they & # x27; re crashing. These tests are compose forLuma, a dummy e-commerce program.
Test 1: Add Item to Cart and Change Quantity
The overarch objective of the initiatory test is to add an detail (in this case, a backpack) to the shopping cart, go to the check page, and eventually conclude the test by changing the quantity of the item.
The entire script looks like this:
1from selenium importwebdriverfrom selenium.webdriver importKeysfrom selenium.webdriver.common.by import By23print(& quot; test example commence & quot;)4driver = webdriver.Chrome()56# Maximize the window sizing7driver.maximize_window()89# Navigate to the URL10driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)11print(driver.title)1213searchBtn = driver.find_element(By.ID,& # x27; search & # x27;)searchBtn.send_keys(& quot; backpack & quot;)14searchBtn.send_keys(Keys.ENTER)1516backpack = driver.find_element(By.XPATH,& quot; // * [contains (text (), & # x27; Driven Backpack & # x27;)] & quot;)backpack.click()1718addToCart = driver.find_element(By.ID,& # x27; product-addtocart-button & # x27;)19addToCart.click()2021cart = driver.find_element(By.XPATH,& quot; //a [normalize-space () = & # x27; shop cart & # x27;] & quot;)22cart.click()2324quantity = driver.find_element(By.XPATH,& quot; /html [1] /body [1] /div [2] /main [1] /div [3] /div [1] /div [2] /form [1] /div [1] /table [1] /tbody [1] /tr [1] /td [3] /div [1] /div [1] /label [1] /input [1] & quot;)25quantity.clear()26quantity.send_keys(& quot; 2 & quot;)2728print(& quot; detail quantity changed successfully & quot;)
During the test run, your code will successfully run through the entire playscript until it & # x27; s time to navigate to the checkout page.
This is because you & # x27; ll hit a synchronised load screen between the merchandise page and append the particular to check. Since page loads aren & # x27; t immediate, you & # x27; ll inevitably run into matter if you & # x27; re not expend a wait bid.
In the future footstep, the quantity table on the check page should be cleared out. But due to synchronization issues, you & # x27; ll instead get aNoSuchElementException error:
1NoSuchElementException: Message: no such element: Ineffectual to locate constituent: {& quot; method & quot;: & quot; xpath & quot;, & quot; chooser & quot;: & quot; //a [normalize-space () = & # x27; shopping cart & # x27;] & quot;}
Test 2: Get an Item in Size Large and Color Black
The objective of the 2d test is to navigate to Luma and choose a large, black discrepancy of the Hero Hoodie.
The full book looks like this:
1from selenium import webdriver2from selenium.webdriver.common.by import By34print(& quot; trial case started & quot;)5driver = webdriver.Chrome()67# Maximize the window size8driver.maximize_window()910# Navigate to the URL11driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)12print(driver.title)1314largeSize = driver.find_element(By.XPATH,15& quot; //div [@ class= & # x27; swatch-opt-158 & # x27;] //div [@ id= & # x27; option-label-size-143-item-169 & # x27;] & quot;)16largeSize.click()1718blackColor= driver.find_element(By.XPATH,& quot; //div [@ id= & # x27; option-label-color-93-item-49 & # x27;] & quot;)19blackColor.click()2021addToCart = driver.find_element(By.XPATH,& quot; /html [1] /body [1] /div [2] /main [1] /div [3] /div [1] /div [2] /div [3] /div [1] /div [1] /ol [1] /li [4] /div [1] /div [1] /div [3] /div [1] /div [1] /form [1] /button [1] & quot;)22addToCart.click()2324cart = driver.find_element(By.XPATH,& quot; //a [@ class= & # x27; action showcart & # x27;] & quot;)25cart.click()2627topCartButton= driver.find_element((By.XPATH,& quot; //a [@ class= & # x27; activity showcart & # x27;] & quot;))28topCartButton.click()2930product = driver.find_element(By.XPATH,& quot; //a [@ data-bind= & # x27; attr: {href: product_url}, html: product_name & # x27;] & quot;)3132print(product.text)
After navigating to the dummy store, the Python script will scan the DOM to find and click the & quot; L & quot; size option for the Hero Hoodie. When it reach the size options, you & # x27; ll get aNoSuchElementException:
1NoSuchElementException: Message: no such factor: Unable to situate element: {& quot; method & quot;: & quot; xpath & quot;, & quot; selector & quot;: & quot; //div [@ class= & # x27; swatch-opt-158 & # x27;] //div [@ id= & # x27; option-label-size-143-item-169 & # x27;] & quot;}
The reason the test will fail is because the DOM won & # x27; t be able to detect the & quot; L & quot; sizing. When corroborate the item name from the cart, it will also fail due to synchronization issue.
Test 3: Use Navigation Bar to Search Men & # x27; s Pants
The tertiary test uses the navigation bar to hover over the & quot; Men & quot; menu item, hover over the & quot; Bottoms & quot; choice, and click the & quot; Pants & quot; button.
The entire hand looks like this:
1from selenium import webdriver2from selenium.webdriver importActionChains3from selenium.webdriver.common.by import By45print(& quot; test case started & quot;)6driver = webdriver.Chrome()78# Maximize the window size9driver.maximize_window()1011# Navigate to the URL12driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)13print(driver.title)1415# The Action class, a built-in feature in Selenium that automates actions accomplish by your keyboard and shiner, hovers over the & quot; Bottoms & quot; option to reveal both the & quot; Pants & quot; and & quot; Shorts & quot; buttons16menTab = driver.find_element(By.XPATH,& quot; /html [1] /body [1] /div [2] /div [1] /div [1] /div [2] /nav [1] /ul [1] /li [3] /a [1] /span [2] & quot;)17action =ActionChains(driver)18action.move_to_element(menTab).perform()1920bottomsButton= driver.find_element(By.ID,& quot; ui-id-18 & quot;)21action =ActionChains(driver)22action.move_to_element(bottomsButton).perform()2324# Conclude the examination run by implementing a click command on the & quot; Pants & quot; button that leads you to the Men & # x27; s Pants page25pantsButton= driver.find_element(By.ID,& quot; ui-id-23 & quot;)26pantsButton.click()
When you run the test in an incorporate development environment (IDE) such asPyCharm, you & # x27; ll most immediately get a ` NoSuchElementException ` since Selenium won & # x27; t be capable to blame up the HTML element from the DOM:
1NoSuchElementException: Message: no such element: Unable to locate element: {& quot; method & quot;: & quot; xpath & quot;, & quot; selector & quot;: & quot; /html [1] /body [1] /div [2] /div [1] /div [1] /div [2] /nav [1] /ul [1] /li [3] /a [1] /span [2] & quot;}
Because elements in seafaring bar are cover in nested HTML elements, they are prone to crash without a wait command.
SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.
Adding Selenium Wait Commands
Now, let & # x27; s see how these three tests can be improved by adding some of Selenium & # x27; s expect dictation.
Improving Test 1 with the Implicit Wait Command
The implicit wait bidding recite the driver to pause for an allotted amount of clip to allow the HTML factor to load into the DOM. You should therefore use an implicit wait if you & # x27; re conversant with the UI page and element load times.
Using an implicit wait is fabulously useful for the inaugural trial scenario above. During the test run, a synchronized loading screen between the product page and checkout page causes the trial to crash.
An implicit wait aid to handle the interruption between the two screens. By simply bestowdriver.implicitly_wait (5), the IDE waits five seconds for the synchronising to complete before moving to the future step.
The full script with the implicit wait command looks like this:
1from selenium import webdriver2from selenium.webdriver import Keys3from selenium.webdriver.common.by import By45print(& quot; examination event get & quot;)6driver = webdriver.Chrome()78# Maximize the window sizing9driver.maximize_window()1011# Navigate to the URL12driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)13print(driver.title)1415searchBtn = driver.find_element(By.ID,& # x27; lookup & # x27;)16searchBtn.send_keys(& quot; backpack & quot;)17searchBtn.send_keys(Keys.ENTER)1819backpack = driver.find_element(By.XPATH,& quot; // * [contains (schoolbook (), & # x27; Driven Backpack & # x27;)] & quot;)20backpack.click()2122addToCart = driver.find_element(By.ID,& # x27; product-addtocart-button & # x27;)23addToCart.click()2425# Implicit wait26driver.implicitly_wait(5)2728cart = driver.find_element(By.XPATH,& quot; //a [normalize-space () = & # x27; shopping cart & # x27;] & quot;)29cart.click()3031quantity = driver.find_element(By.XPATH,& quot; /html [1] /body [1] /div [2] /main [1] /div [3] /div [1] /div [2] /form [1] /div [1] /table [1] /tbody [1] /tr [1] /td [3] /div [1] /div [1] /label [1] /input [1] & quot;)32quantity.clear()33quantity.send_keys(& quot; 2 & quot;)34print(& quot; point measure changed successfully & quot;)
Improving Test 2 with the Explicit Wait Command
The explicit wait dictation tells the driver to wait until certain conditions are present in the DOM—for instance, until an HTML factor is clickable or visible—before throwing an exception. It & # x27; s considered a more & quot; intelligent & quot; version of an implicit wait, since it allows the code to pause until certain weather are met.
However, the syntax of an explicit waiting is more complex than an inexplicit wait. You take to call the explicit wait with the undermentioned code:
1wait =WebDriverWait(driver,<number of seconds>)
You then parameterize your explicit wait based on anticipate conditions (EC), which can involve waiting until the element is seeable or clickable, among many other possibility. Some of themost commonly used ECsduring testing are element_to_be_clickable, visibility_of_element_located, element_to_be_selected, and alert_is_present.
When writing your explicit wait, the syntax is:
1wait.until(EC.<expected conditiontype>((By.XPATH,& quot; & lt; element xpath & gt; & quot;)))
Using an denotative waiting to improve the second examination scenario is useful in two shipway. Since the IDE has hassle detect the size option in the DOM, you can implement an expressed waiting to wait until the factor is clickable.
Another failure occurs due to synchronization issues after adding your particular to the cart itself. You can add an explicit wait until the cart element is seeable.
The entire script with explicit waits looks like this:
1from selenium import webdriver2from selenium.webdriver.common.by import By3from selenium.webdriver.support.wait importWebDriverWait4from selenium.webdriver.support importexpected_conditionsas EC56print(& quot; test case commence & quot;)7driver = webdriver.Chrome()89# Maximize the window size10driver.maximize_window()1112# Navigate to the URL13driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)14print(driver.title)1516# Explicit postponement17wait =WebDriverWait(driver,10)18largeSize = wait.until(EC.element_to_be_clickable((By.XPATH,& quot; //div [@ class= & # x27; swatch-opt-158 & # x27;] //div [@ id= & # x27; option-label-size-143-item-169 & # x27;] & quot;)))19largeSize.click()2021blackColor= driver.find_element(By.XPATH,& quot; //div [@ id= & # x27; option-label-color-93-item-49 & # x27;] & quot;)22blackColor.click()2324addToCart = driver.find_element(By.XPATH,& quot; /html [1] /body [1] /div [2] /main [1] /div [3] /div [1] /div [2] /div [3] /div [1] /div [1] /ol [1] /li [4] /div [1] /div [1] /div [3] /div [1] /div [1] /form [1] /button [1] & quot;)25addToCart.click()2627cart = driver.find_element(By.XPATH,& quot; //a [@ class= & # x27; action showcart & # x27;] & quot;)28cart.click()2930# Explicit wait31topCartButton= wait.until(EC.visibility_of_element_located((By.XPATH,& quot; //a [@ class= & # x27; activity showcart & # x27;] & quot;)))32topCartButton.click()3334product = wait.until(EC.visibility_of_element_located((By.XPATH,& quot; //a [@ data-bind= & # x27; attr: {href: product_url}, html: product_name & # x27;] & quot;)))3536print(product.text)
Improving Test 3 with the Fluent Wait Command
Alike to an explicit wait, a fluent wait tells the driver to wait until certain ECs are met in the DOM before throwing an exception. Fluent waiting are also called & quot; smart waits & quot; because they don & # x27; t wait the maximum time determine in your code; they break until the element is discoverable in the DOM.
So, if your component lade at different times—for illustration, if page load takes fifteen sec vs. a active push that takes three seconds—or if you & # x27; re unaware of how long elements take to load, you should opt for fluent waits alternatively of explicit waits.
The syntax of fluent waits is more customizable but likewise more complex than either implicit or explicit waits. It comes with two features: poll_frequency and ignored_exceptions. With poll_frequency, you can tell your script to keep rechecking constituent every limit number of bit. If you opt not to use poll_frequency, the default is 500 milliseconds.
You can use ignored_exceptions to tell your script to halt exception error (such as NoSuchElementException and ElementNotVisibleException). Use it in example element load times are long than usual, and you like to recheck the element according to poll intervals.
When writing your fluent hold, the syntax is:
1WebDriverWait(driver,<number of sec>,poll_frequency=<figure of s>,ignored_exceptions=[<exception type>,<exception type>])2wait.until(EC.<expected conditiontype>((By.XPATH,& quot; & lt; element xpath & gt; & quot;)))
In the 3rd test scenario, fluent waits can be used to vacillate over the & quot; Men & quot; navigation bar option and the & quot; Bottoms & quot; option. You can use a fluent wait to make the IDE wait ten seconds before using poll_frequency to recheck the DOM every one s for the specified HTML element.
The entire codification with fluent waits looks like this:
1from selenium import webdriver2from selenium.webdriver importActionChains3from selenium.webdriver.common.by import By4from selenium.webdriver.support.wait importWebDriverWait5from selenium.webdriver.support importexpected_conditionsas EC6from selenium.common importElementNotVisibleException,ElementNotSelectableException78print(& quot; trial case started & quot;)9driver = webdriver.Chrome()1011# Maximize the window sizing12driver.maximize_window()1314# Navigate to the URL15driver.get(& quot; https: //magento.softwaretestingboard.com/ & quot;)16print(driver.title)1718# Fluent postponement19wait =WebDriverWait(driver,10,poll_frequency=1,ignored_exceptions=[ElementNotVisibleException,ElementNotSelectableException])2021menTab = wait.until(EC.visibility_of_element_located((By.XPATH,& quot; /html [1] /body [1] /div [2] /div [1] /div [1] /div [2] /nav [1] /ul [1] /li [3] /a [1] /span [2] & quot;)))22action =ActionChains(driver)23action.move_to_element(menTab).perform()2425bottomsButton= wait.until(EC.visibility_of_element_located((By.ID,& quot; ui-id-18 & quot;)))26action =ActionChains(driver)27action.move_to_element(bottomsButton).perform()2829pantsButton= driver.find_element(By.ID,& quot; ui-id-23 & quot;)30pantsButton.click()3132print(driver.title)
Are You Using Selenium Wait Commands?
Whether you & # x27; re loading a new page or research for nested HTML elements, Selenium & # x27; s look bidding can help keep your test pass from continuously crashing.
When comparing the three commands, proceed in judgement that even though using the unquestioning wait command is the simplest, it retard down test execution. Use it if you & # x27; re just getting started, but then challenge yourself to progress to explicit waits and fluent waits.
If you want the most comprehensive mechanization tool to accelerate your releases, see out. Sauce Labs lets you and rush up development with parallel. Developers can leave the hassle of lay up and maintaining infrastructure to Sauce Labs, so they can do things that matter.
More Selenium Resources
Share this position
Need to test right now? Get started free.
Ship codification that comport exactly as it should, faster.
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free

