0
0
Selenium Pythontesting~5 mins

Window handles in Selenium Python

Choose your learning style9 modes available
Introduction

Window handles help you switch between different browser windows or tabs during automated tests.

When your test opens a new browser tab or window and you need to interact with it.
When you want to verify content in a popup window.
When you need to close a child window and return to the main window.
When testing multi-window workflows like login popups or external links.
When handling alerts or dialogs that open in new windows.
Syntax
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.

Examples
Gets all open window handles and prints them as a list.
Selenium Python
handles = driver.window_handles
print(handles)
Stores and prints the handle of the current (main) window.
Selenium Python
main_window = driver.current_window_handle
print(main_window)
Switches control to the second window opened (index 1).
Selenium Python
driver.switch_to.window(handles[1])
Sample Program

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.

Selenium Python
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()
OutputSuccess
Important Notes

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.

Summary

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.