Hard Wait in Selenium with Python
In Selenium automation, Hard Wait means forcing the program to pause execution for a fixed amount of time, regardless of whether the element is ready or not.
In Python, hard wait is implemented using the built-in time.sleep() function.
🔹 What is Hard Wait?
Hard wait makes the script stop completely for a specified time. The execution resumes only after the time is over — even if the element is already available.
Syntax:
import time time.sleep(seconds)
🔹 Example: Hard Wait in Selenium with Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://example.com")
# Hard wait for 5 seconds
time.sleep(5)
login_button = driver.find_element(By.ID, "login")
login_button.click()
driver.quit()
🔹 Where Hard Wait is Used?
- Debugging test scripts
- Demo automation
- Temporary wait for page load
- Testing animations or transitions
❌ Disadvantages of Hard Wait
- Slows down test execution
- Wastes time if element loads early
- Fails if element loads late
- Not dynamic
- Makes framework inefficient
🔹 Hard Wait vs Dynamic Wait
| Hard Wait | Dynamic Wait (Explicit/Implicit) |
|---|---|
| Fixed time wait | Waits until condition is met |
time.sleep() |
WebDriverWait / implicitly_wait() |
| Always waits full time | Stops as soon as element is ready |
| Slow execution | Fast and optimized |
🔹 Best Practice
Hard wait should be used only when absolutely necessary. For real-time automation frameworks, always prefer:
- Explicit Wait (
WebDriverWait) - Implicit Wait (
driver.implicitly_wait())
🔹 Alternative (Recommended Way)
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) login_button = wait.until(EC.element_to_be_clickable((By.ID, "login"))) login_button.click()
🔹 Interview Questions
- What is hard wait in Selenium?
- Which function is used for hard wait in Python?
- Why hard wait is not recommended?
- Difference between hard wait and explicit wait?
- When should we use hard wait?
🔹 Conclusion
Hard wait is the simplest form of waiting mechanism in Selenium, but it is not suitable for real-world automation frameworks. Professional automation always uses dynamic waits for stability, speed, and reliability.
No comments:
Post a Comment