Check if a page is completely loaded or not in Selenium web driver in Python
Hello programmers, in this tutorial we will see how to check if a page is completely loaded using the Selenium web driver in Python.
Here we will see a demo on how to use the Selenium web driver to check for a page is completely loaded or not in Python.
Download the selenium python using the following command in your command prompt.
pip install selenium
For checking for a page is completely loaded or not, we use the concept of waits. Check out the Selenium Wait in Python blog for more details.
An implicit wait is used to wait for a certain time for a particular element that is not available immediately whereas the explicit wait is used to meet a certain condition to occur.
For checking the page is completely loaded, we use explicit wait conditions to check for it.
Before running the code, we need to install the chrome driver and executable file path location to the system path.
Checking if a page is completely loaded or not using Selenium in Python
Given below is the illustration of using the explicit wait function to check for the load of the page.
#Importing necessary libraries from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #wait for page load function def seleniumPageLoad(): #creating a webdriver object driver = webdriver.Chrome(executable_path='C:/path/to/dir/chromedriver.exe') driver.maximize_window() #maximize window size driver.get("https://www.codespeedy.com/") #opening the url try: ele = WebDriverWait(driver, 10).until( #using explicit wait for 10 seconds EC.presence_of_element_located((By.CSS_SELECTOR, "h2")) #checking for the element with 'h2'as its CSS ) print("Page is loaded within 10 seconds.") except: print("Timeout Exception: Page did not load within 10 seconds.") #driver if __name__ == "__main__": seleniumPageLoad() #call the function
Page is loaded within 10 seconds.
Within the function, we use the ‘.get()’ method to open the URL and then we check for a particular element presence using the explicit wait condition within the ‘try’ block. If the page loads within 10 seconds of the given time, the ‘page is loaded’ statement is printed, else the timeout exception error occurs.
Leave a Reply