When using Selenium for automated testing, you frequently encounter scenarios requiring switching between multiple browser windows or tabs. Selenium provides a straightforward method to handle this. Below are the basic steps and examples for switching between multiple windows:
Step 1: Obtain the Current Window Handle
First, obtain the current window handle. This handle is a unique identifier that Selenium uses to manage the window.
pythoncurrent_window_handle = driver.current_window_handle
Step 2: Open a New Window and Obtain All Window Handles
When Selenium operations open a new window or tab, you must retrieve all window handles.
python# Assuming clicking a link opens a new window link = driver.find_element_by_link_text("Open a new window link") link.click() # Obtain all window handles all_window_handles = driver.window_handles
Step 3: Switch to the New Window
Next, iterate through all window handles and switch to a window other than the current one.
pythonfor window_handle in all_window_handles: if window_handle != current_window_handle: driver.switch_to.window(window_handle) break
Step 4: Perform Actions in the New Window
Once switched to the new window, you can perform actions as you would with the original window.
python# Perform actions in the new window, for example: new_window_title = driver.title print(new_window_title)
Step 5: Close the New Window and Switch Back to the Original Window
After completing operations, close the new window and switch back to the original window if necessary.
python# Close the new window driver.close() # Switch back to the original window driver.switch_to.window(current_window_handle)
Example
Assume a webpage containing a link that opens a new window, and we need to verify the title in the new window is correct, then close it and return to the original window.
pythonfrom selenium import webdriver # Initialize WebDriver driver = webdriver.Chrome() # Open webpage driver.get("http://example.com") current_window_handle = driver.current_window_handle # Perform action to open new window link = driver.find_element_by_link_text("Open a new window link") link.click() # Switch to new window all_window_handles = driver.window_handles for window_handle in all_window_handles: if window_handle != current_window_handle: driver.switch_to.window(window_handle) break # Verify new window title assert "Expected title" in driver.title # Close new window and switch back driver.close() driver.switch_to.window(current_window_handle) # Close browser driver.quit()
With this approach, you can easily manage multiple windows in Selenium tests and switch between them for operations.