Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set Selenium Python WebDriver default timeout?
Setting default timeout in Selenium Python WebDriver helps prevent tests from hanging indefinitely. Selenium provides two main approaches: set_page_load_timeout() for page loading and implicitly_wait() for element location.
Page Load Timeout
The set_page_load_timeout() method sets a timeout for page loading. If the page doesn't load within the specified time, a TimeoutException is thrown.
Syntax
driver.set_page_load_timeout(timeout_in_seconds)
Example
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import TimeoutException
# Setup WebDriver
service = Service()
driver = webdriver.Chrome(service=service)
try:
# Set page load timeout to 10 seconds
driver.set_page_load_timeout(10)
driver.get("https://www.tutorialspoint.com/")
print("Page loaded successfully")
except TimeoutException:
print("Page load timeout exceeded")
finally:
driver.quit()
Implicit Wait
The implicitly_wait() method sets a default timeout for finding elements. This is a global setting applied to all element location operations throughout the WebDriver session.
Syntax
driver.implicitly_wait(timeout_in_seconds)
Example
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
# Setup WebDriver
service = Service()
driver = webdriver.Chrome(service=service)
try:
# Set implicit wait to 10 seconds
driver.implicitly_wait(10)
driver.get("https://www.tutorialspoint.com/")
# This will wait up to 10 seconds for the element to appear
element = driver.find_element(By.TAG_NAME, "h1")
print(f"Found element: {element.text}")
except Exception as e:
print(f"Error: {e}")
finally:
driver.quit()
Comparison
| Method | Purpose | Scope | Exception |
|---|---|---|---|
set_page_load_timeout() |
Page loading | Entire page | TimeoutException |
implicitly_wait() |
Element location | All find operations | NoSuchElementException |
Best Practices
Use reasonable timeout values − too short may cause false failures, too long slows down test execution. Combine both methods for comprehensive timeout handling:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service()
driver = webdriver.Chrome(service=service)
# Set both timeouts
driver.set_page_load_timeout(30) # 30 seconds for page load
driver.implicitly_wait(10) # 10 seconds for element finding
# Your test code here
driver.get("https://www.tutorialspoint.com/")
Conclusion
Use set_page_load_timeout() to control page loading duration and implicitly_wait() for element location timeouts. Setting both ensures robust test execution without indefinite hanging.
