Window handles 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 # Initialize the Chrome driver with webdriver.Chrome() as driver: wait = WebDriverWait(driver, 10) # Open the main page driver.get('https://example.com/main') original_window = driver.current_window_handle # Click the link that opens a new window wait.until(EC.element_to_be_clickable((By.ID, 'open-new-window'))).click() # Wait for the new window wait.until(EC.number_of_windows_to_be(2)) # Get all window handles windows = driver.window_handles # Switch to the new window for window in windows: if window != original_window: driver.switch_to.window(window) break # Verify the new window title wait.until(EC.title_is('New Window')) assert driver.title == 'New Window', f"Expected title 'New Window' but got '{driver.title}'" # Close the new window driver.close() # Switch back to original window driver.switch_to.window(original_window) # Verify the original window title wait.until(EC.title_is('Main Page')) assert driver.title == 'Main Page', f"Expected title 'Main Page' but got '{driver.title}'"
This script uses Selenium WebDriver with Python to automate the test case.
First, it opens the main page and stores the original window handle.
Then it clicks the link that opens a new window and waits until two windows are open.
It switches to the new window by comparing window handles.
It waits for the new window's title to be 'New Window' and asserts it.
Next, it closes the new window and switches back to the original window.
Finally, it waits for the original window's title to be 'Main Page' and asserts it.
Using explicit waits ensures the script waits for elements and conditions properly.
Using a context manager for the driver ensures the browser closes after the test.
Now add data-driven testing with 3 different links that open different new windows and verify their titles.