Multiple Windows and Tabs
Window Handles
Each window or tab has a unique id called a handle. Selenium controls one window at a time. When a link opens a new tab, your driver is still on the old tab until you switch.
python
driver.get("https://the-internet.herokuapp.com/windows")
original = driver.current_window_handle
print(driver.window_handles) # list of all handles
driver.find_element(By.LINK_TEXT, "Click Here").click()
Switch to the New Window
python
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
for handle in driver.window_handles:
if handle != original:
driver.switch_to.window(handle)
break
print(driver.title) # New Window
print(driver.find_element(By.TAG_NAME, "h3").text)
driver.close() # close the new window
driver.switch_to.window(original) # return to the first one
print(driver.title)
Why wait? The new window needs a moment to open.
number_of_windows_to_be(2) waits until it exists. Without it you may read window_handles too early.
Open a New Tab or Window Yourself (Selenium 4)
python
driver.switch_to.new_window("tab") # opens and switches to a new tab
driver.get("https://www.selenium.dev")
driver.switch_to.new_window("window") # a new separate window
Helper Functions
python
def switch_to_new_window(driver, original_handle):
WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)
new_handle = [h for h in driver.window_handles if h != original_handle][0]
driver.switch_to.window(new_handle)
return new_handle
def switch_to_window_by_title(driver, title_part):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if title_part in driver.title:
return True
return False
Typical Test: Link Opens in a New Tab
python
original = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Terms of Service").click()
switch_to_new_window(driver, original)
assert "terms" in driver.current_url.lower()
driver.close()
driver.switch_to.window(original)
Do not forget to switch back: After
close() the driver has no current window. Commands then fail with NoSuchWindowException until you switch to a valid handle.
Parallel tests: Do not share one driver between threads. Each test should have its own driver (and window).
Conclusion
Store the original handle, wait for the new window, switch to it using window_handles, do your checks, close it and switch back. Use switch_to.new_window to create tabs.
Quick Summary: window_handles + switch_to.window; always return to the original handle.

