Window handles help you switch between different browser windows or tabs during automated tests.
Window handles in Selenium Python
driver.window_handles # Returns a list of all open window handles driver.current_window_handle # Returns the handle of the current window driver.switch_to.window(window_handle) # Switches control to the specified window
Window handles are unique IDs for each open browser window or tab.
You must switch to the desired window before interacting with elements inside it.
handles = driver.window_handles
print(handles)main_window = driver.current_window_handle
print(main_window)driver.switch_to.window(handles[1])This script opens a webpage with a button that opens a new window. It clicks the button, switches to the new window, prints its title, closes it, then switches back to the main window and prints its title again.
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup driver driver = webdriver.Chrome() driver.get('https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open') # Click button to open new window iframe = driver.find_element(By.ID, 'iframeResult') driver.switch_to.frame(iframe) driver.find_element(By.TAG_NAME, 'button').click() # Get window handles handles = driver.window_handles print(f"All window handles: {handles}") # Switch to new window main_window = driver.current_window_handle driver.switch_to.window(handles[1]) print(f"Switched to new window title: {driver.title}") # Close new window driver.close() # Switch back to main window driver.switch_to.window(main_window) print(f"Back to main window title: {driver.title}") driver.quit()
Window handles are strings and unique per browser session.
Always switch back to the main window after closing child windows to avoid errors.
Use explicit waits if the new window takes time to load before switching.
Window handles let you control multiple browser windows or tabs in Selenium.
You get all handles with driver.window_handles and switch with driver.switch_to.window().
Switching windows is essential to interact with elements in popups or new tabs.