- selenium wait for page to load
- example
- selenium wait for page to load
- Use Selenium wait for page to load with Python [Tutorial]
- Why use Selenium Wait For Page To load?
- Different Types of Python Selenium Wait
- Explicit Waits in Selenium Python
- 5. Waits¶
- 5.1. Explicit Waits¶
- 5.2. Implicit Waits¶
- Wait until page is loaded with Selenium WebDriver for Python.
- Example
selenium wait for page to load
Wait for a page to load with Python selenium. In this article you’ll learn how to do that. It’s a bit counter-intuitive.
Selenium lets you automate the browser, but you don’t need time.sleep to wait for the page loading to complete. In fact, it works differently than you may expect.
Related course:
example
selenium wait for page to load
The code block below shows you how to wait for a page load to complete. It uses a timeout. It waits for an element to show on the page (you need an element id).
Then if the page is loaded, it shows page loaded. If the timeout period (in seconds) has passed, it will show the timeout error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
driver.get(‘https://pythonbasics.org’)
timeout = 3
try:
element_present = EC.presence_of_element_located((By.ID, ‘main’))
WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
print(«Timed out waiting for page to load»)
finally:
print(«Page loaded»)
Use Selenium wait for page to load with Python [Tutorial]
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.
One of the primary requisites to automate interactions with a WebElement in the DOM is that it should be visible and interactable. Like me, you would also come across several scenarios where your Selenium Python scripts threw an ElementNotVisibleException.
The failure in the test automation script can be attributed to the presence of dynamic WebElements on the web page. The WebElement under test might not have been loaded on the web page and your test is trying to perform some activity on that WebElement. It is known that dynamic content loading with AJAX is widely used across different web products (or websites). When interacting with dynamic WebElements using Selenium test automation, it is recommended to add Selenium wait for the page to load, so that the element is available for performing tests.
Source
Selenium wait in Python gives additional time for loading of the WebElements in the DOM. In this article, we deep dive into the different types of wait in Selenium WebDriver along with the usage of Selenium wait for page to load in Python.
TABLE OF CONTENT
Why use Selenium Wait For Page To load?
To answer this question, it is essential to understand the ‘where’ and ‘why’ of dynamic page loads. Some of the conditions mentioned below might be known to you or you might have already encountered them.
Case 1: Uploading files
I am sure you might have uploaded some file, image or video on some online platform. You might have noticed that once you select the file, it takes some time to upload the same. ON similar lines, when you try to upload files using Selenium test automation scripts, you will need to implement Selenium Wait in Python for realizing the successful uploading of the file. successfully. If you don’t use the Selenium wait for page to load after upload, you might witness some errors.
Case 2: Delayed confirmation message
Applications like Gmail allow the users to interact and work on a real-time basis. Even though you are able to interact with the application through the email sending usecase, you do not get an immediate confirmation of the delivery. The confirmation depends upon a number of factors like network availability, attached file size, etc.
As a QA engineer, we need to factor in such conditions when planning and performing usability and user acceptance tests. For Python, you will have to implement Selenium Wait for page to load in order to ensure that tests are performed with the necessary WebElements in the DOM.
Case 3: Conditional load of Page Elements
Certain websites have some components or elements hidden, or not visible at an initial stage. They can be interacted with only after some preset conditions are met. For example – On a movie ticketing website, the button for booking a seat becomes available only after some preset time. This is a classic case of conditional loading of page components. To handle such scenarios in test automation scripts, you will need to implement Selenium wait for page to load.
Selenium wait for ensuring the page to load is applicable in other scenarios like skipping the ad in YouTube, lazy loading of images in webpages, and more.
This certification is for professionals looking to develop advanced, hands-on expertise in Selenium automation testing with Python and take their career to the next level.
Here’s a short glimpse of the Selenium Python 101 certification from LambdaTest:
Different Types of Python Selenium Wait
Selenium WebDriver provides a “wait” package to deal with conditions where you need to wait before interacting with target WebElements. You can also leverage Python’s ‘Sleep’ function to wait for a specified interval, however, that approach is not a recommended one!
There are three different ways to implement Selenium Wait in Python for page to load:
Explicit Waits in Selenium Python
Explicit waits are introduced to temporarily freeze the execution of the Selenium test automation script. It makes use of the functions available in Selenium WebDriver’s wait package. The program halts the execution for a specified time or until a certain expected condition is fulfilled.
Explicit waits can be implemented using the WebDriverWait class of Selenium python bindings. Let’s take a look at the WebDriverWait class.
5. Waits¶
These days, most of the web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNotVisibleException exception. Using waits, we can solve this issue. Waiting provides some slack between actions performed — mostly locating an element or any other operation with the element.
Selenium Webdriver provides two types of waits — implicit & explicit. An explicit wait makes WebDriver wait for a certain condition to occur before proceeding further with execution. An implicit wait makes WebDriver poll the DOM for a certain amount of time when trying to locate an element.
5.1. Explicit Waits¶
An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "myDynamicElement")) ) finally: driver.quit()
In the code above, Selenium will wait for a maximum of 10 seconds for an element matching the given criteria to be found. If no element is found in that time, a TimeoutException is thrown. By default, WebDriverWait calls the ExpectedCondition every 500 milliseconds until it returns success. ExpectedCondition will return true (Boolean) in case of success or not null if it fails to locate an element.
Expected Conditions
There are some common conditions that are frequently of use when automating web browsers. Listed below are the names of each. Selenium Python binding provides some convenience methods so you don’t have to code an expected_condition class yourself or create your own utility package for them.
- title_is
- title_contains
- presence_of_element_located
- visibility_of_element_located
- visibility_of
- presence_of_all_elements_located
- text_to_be_present_in_element
- text_to_be_present_in_element_value
- frame_to_be_available_and_switch_to_it
- invisibility_of_element_located
- element_to_be_clickable
- staleness_of
- element_to_be_selected
- element_located_to_be_selected
- element_selection_state_to_be
- element_located_selection_state_to_be
- alert_is_present
from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))
The expected_conditions module contains a set of predefined conditions to use with WebDriverWait.
Custom Wait Conditions
You can also create custom wait conditions when none of the previous convenience methods fit your requirements. A custom wait condition can be created using a class with __call__ method which returns False when the condition doesn’t match.
class element_has_css_class(object): """An expectation for checking that an element has a particular css class. locator - used to find the element returns the WebElement once it has the particular css class """ def __init__(self, locator, css_class): self.locator = locator self.css_class = css_class def __call__(self, driver): element = driver.find_element(*self.locator) # Finding the referenced element if self.css_class in element.get_attribute("class"): return element else: return False # Wait until an element with has class 'myCSSClass' wait = WebDriverWait(driver, 10) element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))
polling2 Library
You may also consider using polling2 library which you need to install separately.
5.2. Implicit Waits¶
An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available. The default setting is 0 (zero). Once set, the implicit wait is set for the life of the WebDriver object.
from selenium import webdriver driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("http://somedomain/url_that_delays_loading") myDynamicElement = driver.find_element_by_id("myDynamicElement")
Wait until page is loaded with Selenium WebDriver for Python.
We can wait until the page is loaded with Selenium webdriver. There is a synchronization concept in Selenium which describes implicit and explicit wait. To wait until the page is loaded we shall use the explicit wait concept.
The explicit wait is designed such that it is dependent on the expected condition for a particular behavior of an element. For waiting until the page is loaded we shall use the expected condition presence_of_element_loaded for a particular element. Once the wait time is elapsed, the timeout error shall be thrown.
To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class. Let us check the presence of the element below on the page and verify if the page is loaded.
Example
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") driver.get("https://www.tutorialspoint.com/about/about_careers.htm") // presence_of_element_located expected condition wait for 8 seconds try: w = WebDriverWait(driver, 8) w.until(expected_conditions.presence_of_element_located((By.TA G_NAME,"h1"))) print("Page load happened") exception TimeException: print("Timeout happened no page load") driver.close()