0
0
Selenium Pythontesting~5 mins

Handling multiple pages in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes websites open new pages or tabs. We need to switch between them to test properly.

When clicking a link opens a new tab or window.
When a popup or new page appears after a button click.
When testing login flows that redirect to another page.
When verifying content on multiple pages opened from one action.
Syntax
Selenium Python
driver.window_handles
# List of all open window/tab IDs

driver.switch_to.window(window_handle)
# Switch control to the window/tab with given ID

window_handles gives a list of all open pages.

Use switch_to.window() to change focus to another page.

Examples
Get all open window IDs and print them.
Selenium Python
all_windows = driver.window_handles
print(all_windows)
Switch to the second tab or window opened.
Selenium Python
driver.switch_to.window(driver.window_handles[1])
Store the current window ID to switch back later.
Selenium Python
main_window = driver.current_window_handle
# Save current window ID for later use
Sample Program

This script opens a page with a button that opens a new window. It switches to the new window, prints its title, closes it, then switches back and prints the main window's title.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open first page
driver.get('https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open')

# Save main window handle
main_window = driver.current_window_handle

# Click button that opens new window
# Switch to iframe first because button is inside iframe
iframe = driver.find_element(By.ID, 'iframeResult')
driver.switch_to.frame(iframe)

button = driver.find_element(By.TAG_NAME, 'button')
button.click()

# Wait for new window to open
time.sleep(2)

# Get all window handles
all_windows = driver.window_handles

# Switch to new window (last one)
driver.switch_to.window(all_windows[-1])

# Print title of new window
print('New window title:', driver.title)

# Close new window
driver.close()

# Switch back to main window
driver.switch_to.window(main_window)

# Print title of main window
print('Main window title:', driver.title)

driver.quit()
OutputSuccess
Important Notes

Always save the main window handle before opening new windows.

Switch to iframes if elements are inside them before clicking.

Use time.sleep() carefully; better to use explicit waits in real tests.

Summary

Use driver.window_handles to get all open pages.

Switch between pages with driver.switch_to.window().

Save main window handle to return after closing new pages.