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 WebDriver
with webdriver.Chrome() as driver:
driver.get('https://example.com/multi-window') # Replace with actual URL
original_window = driver.current_window_handle
# Click link that opens new window
link = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, 'open-new-window'))
)
link.click()
# Wait for new window
WebDriverWait(driver, 10).until(EC.new_window_is_opened)
# Get all window handles
windows = driver.window_handles
# Switch to new window
for window in windows:
if window != original_window:
driver.switch_to.window(window)
break
# Verify new window title or URL
WebDriverWait(driver, 10).until(EC.title_contains('New Window'))
assert 'new-window' in driver.current_url, f"Expected 'new-window' in URL but got {driver.current_url}"
# Switch back to original window
driver.switch_to.window(original_window)
# Verify original window title or URL
WebDriverWait(driver, 10).until(EC.title_contains('Main Page'))
assert 'multi-window' in driver.current_url, f"Expected 'multi-window' in URL but got {driver.current_url}"
This script opens a web page that has a link opening a new window. It stores the original window handle first. Then it clicks the link and waits until a new window opens.
It collects all window handles and switches to the one that is not the original. Then it waits for the new window's title to contain expected text and asserts the URL contains expected substring.
After verification, it switches back to the original window and verifies its title and URL similarly.
Explicit waits ensure the windows are fully loaded before assertions. Using window handles avoids hardcoding window indices, making the test reliable.