Selenium + Python · Lesson 18 of 43

0/43 done

Module 18: Browser Navigation & Windows

18. Window Handles & Multi-Tab Switching in Python

16 minlesson

Your task

Implement switch_to_new_tab(driver, parent_handle):

  1. Iterate driver.window_handles.
  2. If handle != parent_handle, driver.switch_to.window(handle) and return True.
  3. Return False if no new tab found.

Write it in the editor, then press Check answer (Ctrl + Enter).

Switching Windows & Tabs

python
parent_handle = driver.current_window_handle

driver.find_element(By.ID, "open-tab-btn").click()

for handle in driver.window_handles:
    if handle != parent_handle:
        driver.switch_to.window(handle)
        break

print("New tab title:", driver.title)
driver.close()
driver.switch_to.window(parent_handle)

Key Takeaways & Walkthrough Summary

When a link opens in a new tab, Selenium does not automatically switch focus. In this lesson, you will master current_window_handle, window_handles, and driver.switch_to.window() to navigate multi-window flows. Let's switch windows!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What happens if I try to find an element after closing a tab?

If you don't switch back to an active window using switch_to.window(), Selenium raises NoSuchWindowException.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip