How to Switch Window in Selenium Python: Simple Guide
In Selenium Python, you switch between browser windows or tabs using
driver.switch_to.window(window_handle). You get the window handles with driver.window_handles and pass the desired handle to switch focus.Syntax
The main syntax to switch windows in Selenium Python is:
driver.window_handles: Returns a list of all open window handles.driver.switch_to.window(window_handle): Switches the driver's focus to the specified window handle.
You use these to move control from one browser window or tab to another.
python
driver.switch_to.window(window_handle)
Example
This example opens a website, clicks a link that opens a new tab, then switches to the new tab and prints its title.
python
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup WebDriver (make sure chromedriver is in PATH) driver = webdriver.Chrome() # Open initial page driver.get('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_link_target') # Switch to iframe where the link is iframe = driver.find_element(By.ID, 'iframeResult') driver.switch_to.frame(iframe) # Click the link that opens a new tab link = driver.find_element(By.LINK_TEXT, 'Visit W3Schools.com!') link.click() # Wait for new tab to open time.sleep(2) # Get window handles handles = driver.window_handles # Switch to the new window (last handle) driver.switch_to.window(handles[-1]) # Print the title of the new tab print(driver.title) # Close driver driver.quit()
Output
W3Schools Online Web Tutorials
Common Pitfalls
Common mistakes when switching windows include:
- Not waiting for the new window to open before switching.
- Using an incorrect or stale window handle.
- Not switching back to the original window if needed.
Always get fresh driver.window_handles after opening new windows and use explicit waits if possible.
python
from selenium.common.exceptions import NoSuchWindowException # Wrong way: switching before new window opens try: driver.switch_to.window('non_existent_handle') except NoSuchWindowException: print('Window handle not found') # Right way: get handles after new window opens handles = driver.window_handles if len(handles) > 1: driver.switch_to.window(handles[-1])
Output
Window handle not found
Quick Reference
| Action | Code Snippet |
|---|---|
| Get all window handles | driver.window_handles |
| Switch to a window | driver.switch_to.window(window_handle) |
| Get current window handle | driver.current_window_handle |
| Close current window | driver.close() |
| Switch back to original window | driver.switch_to.window(original_handle) |
Key Takeaways
Use driver.window_handles to get all open windows or tabs.
Switch windows with driver.switch_to.window(window_handle).
Always get fresh window handles after opening new windows.
Wait for new windows to open before switching to avoid errors.
Remember to switch back to the original window if needed.