When a web test opens a new browser window or tab, the test must switch to it to interact with its content. Without switching, the test stays on the original window and cannot see or control the new one.
Why multi-window scenarios need switching in Selenium Python
driver.switch_to.window(window_handle)
window_handle is a unique ID for each open window or tab.
You get window handles using driver.window_handles, which returns a list of all open windows.
main_window = driver.current_window_handle all_windows = driver.window_handles for window in all_windows: if window != main_window: driver.switch_to.window(window)
driver.switch_to.window(driver.window_handles[-1])This test opens a main page, then opens a new tab with another page. It switches to the new tab to print its title, then switches back to the main tab and prints its title again.
from selenium import webdriver from selenium.webdriver.common.by import By import time # Start browser and open main page driver = webdriver.Chrome() driver.get('https://example.com') # Save main window handle main_window = driver.current_window_handle # Simulate opening a new window (for example, clicking a link that opens new tab) # Here we open a new tab manually for demo script = "window.open('https://example.org', '_blank');" driver.execute_script(script) # Wait for new window to open time.sleep(2) # Switch to new window for handle in driver.window_handles: if handle != main_window: driver.switch_to.window(handle) break # Print title of new window print(driver.title) # Switch back to main window driver.switch_to.window(main_window) print(driver.title) driver.quit()
Always switch to the correct window before interacting with elements there.
Window handles are unique strings that identify each open browser window or tab.
Failing to switch windows can cause errors like NoSuchElementException because the test looks in the wrong window.
Tests must switch windows to interact with new tabs or pop-ups.
Use driver.window_handles to get all open windows.
Switch back to the main window when done with others.