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")

selenium wait for page to load

If you are new to selenium, then I highly recommend this book.

Download examples