Sometimes, web tests open new browser windows or tabs. You need to switch to the right window to continue testing.
0
0
Switching between windows in Selenium Python
Introduction
When clicking a link opens a new tab and you want to check its content.
When a popup window appears and you need to interact with it.
When testing multi-window workflows like login or payment popups.
When you want to switch back to the original window after visiting another.
When automating tests that involve multiple browser windows.
Syntax
Selenium Python
driver.switch_to.window(window_handle)
driver is your Selenium WebDriver instance.
window_handle is a string that identifies the window.
Examples
This switches from the main window to the newly opened 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 back to the first opened window.
Selenium Python
driver.switch_to.window(driver.window_handles[0])Sample Program
This script opens a page with a button that opens a new window. It switches to the new window, prints its title, then switches back and prints the original window's title.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup WebDriver options = webdriver.ChromeOptions() options.add_argument('--headless=new') driver = webdriver.Chrome(options=options) try: driver.get('https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open') driver.switch_to.frame('iframeResult') # Click the button to open a new window driver.find_element(By.TAG_NAME, 'button').click() time.sleep(2) # wait for new window to open main_window = driver.current_window_handle all_windows = driver.window_handles # Switch to new window for window in all_windows: if window != main_window: driver.switch_to.window(window) break print('Title of new window:', driver.title) # Switch back to main window driver.switch_to.window(main_window) print('Title of main window:', driver.title) finally: driver.quit()
OutputSuccess
Important Notes
Always store the original window handle before switching.
Use driver.window_handles to get all open windows.
Switching windows is important to interact with elements in the correct window.
Summary
Switching windows lets you control which browser tab or window Selenium works with.
Use driver.switch_to.window() with the window handle to switch.
Remember to switch back to the original window if needed.