How to Handle Multiple Windows in Selenium WebDriver
driver.window_handles to get all window IDs and driver.switch_to.window() to switch between them. This lets you control and test each window separately.Why This Happens
When your test clicks a link or button that opens a new browser window or tab, Selenium stays focused on the original window by default. Trying to interact with elements in the new window without switching causes errors because Selenium doesn't know which window to control.
from selenium import webdriver # Open browser and go to a page driver = webdriver.Chrome() driver.get('https://example.com') # Click a link that opens a new window (assume it does) driver.find_element('link text', 'Open new window').click() # Try to find element in new window without switching new_window_element = driver.find_element('id', 'new-window-element')
The Fix
You must switch Selenium's focus to the new window before interacting with it. Use driver.window_handles to get all window IDs, then switch to the new one with driver.switch_to.window(). After finishing, switch back to the original window if needed.
from selenium import webdriver import time # Open browser and go to a page driver = webdriver.Chrome() driver.get('https://example.com') # Store the original window handle original_window = driver.current_window_handle # Click a link that opens a new window driver.find_element('link text', 'Open new window').click() # Wait for new window to open time.sleep(2) # Loop through all windows and switch to the new one for window_handle in driver.window_handles: if window_handle != original_window: driver.switch_to.window(window_handle) break # Now interact with elements in the new window new_window_element = driver.find_element('id', 'new-window-element') print('Found element in new window:', new_window_element.tag_name) # Switch back to original window driver.switch_to.window(original_window)
Prevention
Always track window handles when your test opens new windows or tabs. Use explicit waits instead of fixed sleeps to wait for windows to open. Switch back to the original window after finishing work in the new one to keep tests clean. Avoid hardcoding window handles; rely on Selenium's window_handles list.
Best practices:
- Store the original window handle before opening new windows.
- Use loops to find and switch to new windows.
- Use explicit waits (like WebDriverWait) to wait for new windows.
- Switch back to the original window after test steps.
Related Errors
Common errors when handling multiple windows include:
- NoSuchElementException: Trying to find elements in a window without switching to it.
- TimeoutException: Waiting for a window that never opens.
- StaleElementReferenceException: Holding references to elements from a closed window.
Quick fixes:
- Always switch to the correct window before interacting.
- Use explicit waits to detect new windows.
- Refresh element references after switching windows.