Explicit waits (WebDriverWait) in Selenium Python - Build an Automation Script
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 from selenium.common.exceptions import TimeoutException # Initialize the Chrome WebDriver with webdriver.Chrome() as driver: driver.get('https://example.com/login') try: # Wait up to 10 seconds until the login button is clickable wait = WebDriverWait(driver, 10) login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn'))) # Click the login button login_button.click() # Wait until URL changes to dashboard wait.until(EC.url_to_be('https://example.com/dashboard')) # Assert the current URL is the dashboard URL assert driver.current_url == 'https://example.com/dashboard', f"Expected URL to be 'https://example.com/dashboard' but got {driver.current_url}" print('Test Passed: Login button clickable and dashboard loaded') except TimeoutException: print('Test Failed: Element not clickable or URL did not change in time')
This script uses Selenium WebDriver with Python to automate the manual test case.
First, it opens the browser and navigates to the login page URL.
Then, it uses WebDriverWait with expected_conditions.element_to_be_clickable to wait up to 10 seconds for the login button to become clickable. This is better than using fixed waits because it waits only as long as needed.
After the button is clickable, it clicks the button.
Next, it waits until the URL changes to the dashboard URL using expected_conditions.url_to_be.
Finally, it asserts that the current URL is the expected dashboard URL to confirm navigation succeeded.
Exceptions like TimeoutException are caught to handle cases where the button never becomes clickable or the URL does not change in time, printing a failure message.
This approach follows best practices by using explicit waits, proper locators, and assertions.
Now add data-driven testing with 3 different login URLs and verify the login button on each page becomes clickable.