0
0
Selenium Pythontesting~5 mins

Why multi-window scenarios need switching in Selenium Python

Choose your learning style9 modes available
Introduction

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.

Testing a website that opens a link in a new tab or window
Handling pop-up windows during a checkout process
Verifying content in a login window that opens separately
Closing a child window and returning to the main window
Switching between multiple tabs to compare information
Syntax
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.

Examples
This code saves the main window handle, then switches to any other open window.
Selenium Python
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)
This switches to the most recently opened window or tab.
Selenium Python
driver.switch_to.window(driver.window_handles[-1])
Sample Program

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.

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

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.

Summary

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.