All All News Products Insights Community

How to switch tabs in Selenium for Python?

Learn how to switch between browser tabs in Selenium with Python using window handles for smooth test automation.

How-to / Tutorials
Web Testing
Selenium
Python
Hero Banner
Smart Summary

Automating browser interactions in Selenium with Python requires mastering tab management, especially for modern web flows that utilize new tabs for authentication, payments, or external links. By understanding how to leverage `window_handles` and `switch_to.window()`, you can effectively navigate between these tabs, ensuring your test scripts accurately follow user journeys and maintain control.

  • Mastering Tab Switching: Utilize `driver.window_handles` to access a list of all open tab IDs and `driver.switch_to.window()` to activate a specific tab, enabling seamless navigation in multi-tab scenarios.
  • Essential Navigation Techniques: Employ `driver.current_window_handle` to store and return to the original tab, and loop through `driver.window_handles` to interact with or validate content in all open tabs.
  • Enhancing Test Reliability: Implement best practices such as storing the initial tab handle, using explicit waits before switching, closing unnecessary tabs, validating navigation, and logging tab activity to create robust and maintainable Selenium tests.
Good response
Bad response
|
Copied
>
Read more
Blog / Insights /
How to switch tabs in Selenium for Python?

How to switch tabs in Selenium for Python?

Senior Quality Engineer Updated on

Modern web apps often open a new browser tab for login flows, payment pages, documentation links, or social sharing. When that happens, your test has to move with the browser. If Selenium keeps running in the original tab, it will miss what the user actually sees in the new one.

In this guide, you'll learn how to switch tabs in Selenium with Python using the most reliable patterns for modern test automation. This is sometimes called switching windows, or simply handling tabs in Selenium, but the underlying mechanics are the same. We’ll cover:

  • How tab and window handling works in Selenium
  • The best modern way to open a new tab in Selenium 4
  • How to switch, return, and close tabs safely
  • How to work with more than two tabs
  • Common tab-related failures and how to avoid them
  • Why teams often use Katalon to simplify multi-tab automation at scale

THE SHORT ANSWER

To switch tabs in Selenium with Python, get the current tab handle with driver.current_window_handle, open or detect the new tab, then switch to it with driver.switch_to.window(...). In Selenium 4, the cleanest way to open a new tab is driver.switch_to.new_window('tab'). For stability, wait until the new tab exists before switching and re-locate elements after changing tabs.

How tab switching works in Selenium

In Selenium, tabs and windows are handled through the same API. Each browser tab gets a unique window handle, and Selenium uses that handle to move control from one tab to another.

The two most important pieces are:

  • driver.current_window_handle: the handle of the active tab
  • driver.window_handles: a list of every open tab or window

This means tab handling and window handling are conceptually the same in Selenium. The only difference is what the browser chooses to open.

Best modern way to open a new tab in Selenium

If you're using Selenium 4, the best option is the native API:

Python
driver.switch_to.new_window('tab')
driver.get('https://example.com')

This is more reliable than keyboard shortcuts and clearer than JavaScript-based workarounds. If you need to support older patterns, you can still use:

Python
driver.execute_script("window.open('https://example.com', '_blank')")

Keyboard shortcuts such as Ctrl+T or Command+T can work in some cases, but they are more browser-dependent and less reliable in automated test runs.

How to switch to a new tab in Selenium Python

Here is a stable pattern that stores the original tab, opens a new one, waits for it, and switches safely:

Python
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
driver.get("https://katalon.com")

original_tab = driver.current_window_handle
existing_tabs = driver.window_handles.copy()

driver.switch_to.new_window('tab')
driver.get("https://example.com")

WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == len(existing_tabs) + 1)

new_tab = [handle for handle in driver.window_handles if handle not in existing_tabs][0]
driver.switch_to.window(new_tab)
print("Now on:", driver.title)

This approach is safer than assuming the second tab is always at index 1, especially in longer or more dynamic sessions.

When do you need to switch tabs?

Many test flows open a new tab as part of the normal user journey. Common examples include:

  • Links with target="_blank": outbound links or help pages often open separately. See our guide on clicking links in Selenium for the click side of this flow.
    Open in New Tab in HTML
  • OAuth and SSO flows: login providers may open a popup or secondary tab before returning users to the app.
  • Payment gateways: checkout flows often redirect into Stripe, PayPal, or another secure tab.
  • Social sharing: "Share" buttons commonly open a pre-filled post in a new tab.

How to switch tabs by index

If you know the tab order and your flow is simple, you can switch by list position:

Python
tabs = driver.window_handles
if len(tabs) > 1:
    driver.switch_to.window(tabs[1])
    print("Switched to tab at index 1")

This works, but it is usually better to switch by comparing handles rather than assuming a fixed order.

How to switch back to the original tab

Once you finish working in the secondary tab, switch back using the original handle you stored earlier:

Python
driver.switch_to.window(original_tab)
print("Back on main tab")

Saving the original handle at the start of the flow is one of the simplest ways to make tab automation more reliable.

How to close a tab in Selenium

Use the right command for the job:

  • driver.close() closes only the active tab.
  • driver.quit() ends the entire browser session.

Here's the safe pattern:

Python
driver.get("https://katalon.com")
original_tab = driver.current_window_handle

driver.switch_to.new_window('tab')
driver.get("https://example.com")

driver.close()
driver.switch_to.window(original_tab)

How to get the current tab and all open tabs

To inspect what is open and which tab is active, use:

Python
main_tab = driver.current_window_handle
all_tabs = driver.window_handles

for handle in all_tabs:
    driver.switch_to.window(handle)
    print("Tab title:", driver.title)

This is especially useful for debugging flows that open multiple tabs unexpectedly.

Working with more than two tabs

The same pattern scales to three or more tabs. Loop through the handles, inspect each tab, and return to the original when finished:

Python
driver.get("https://katalon.com")
original_tab = driver.current_window_handle

driver.switch_to.new_window('tab')
driver.get("https://example.com")

driver.switch_to.new_window('tab')
driver.get("https://google.com")

for index, handle in enumerate(driver.window_handles, start=1):
    driver.switch_to.window(handle)
    print(f"Tab {index} title:", driver.title)

driver.switch_to.window(original_tab)

Best practices for switching tabs in Selenium Python

  • Store the original handle early: it gives you a safe return point.
  • Wait for the new tab to exist: Selenium can move faster than the browser. An explicit wait on the handle count works well here.
  • Prefer handle comparison over fixed indexes: this avoids brittle tests.
  • Re-locate elements after switching: previously found elements can become stale.
  • Validate where you landed: check the title or URL after each switch.
  • Close tabs you no longer need: this keeps multi-tab flows easier to manage.
  • Test in headless mode too: some browsers behave slightly differently in CI.

Common issues when switching tabs in Selenium

Symptom Likely cause Fix
New tab is not detected The script switches too quickly Wait for the expected number of window handles before switching
NoSuchWindowException The tab was already closed or the handle is invalid Confirm the handle still exists in driver.window_handles
Stale element errors after switching Elements were located in a different tab context Re-locate the element after switching to the active tab

Why choose Katalon to automate tests?

Katalon-as-top-automation-testing-tool

Katalon is an automation platform built on Selenium that helps teams handle browser workflows with less manual overhead. Instead of wiring tab logic together from scratch every time, teams can use built-in browser keywords, execution infrastructure, reporting, and maintenance tools in one place.

With Katalon, teams get:

  • Unified platform: design, execution, management, and reporting in one system.
  • Cross-browser coverage: run tests across a wide mix of browser and OS environments.
  • Scalable execution: support for parallel runs and CI/CD-connected workflows.
  • Smarter maintenance: self-healing capabilities reduce locator-related flakiness.
  • Built-in analytics: dashboards and reports help teams understand quality trends faster.

To learn more, visit the Katalon Docs or explore guided learning paths in Katalon Academy.

Want to explore what Katalon can do for your team? Request a demo to see how it helps teams automate faster with less effort.

True Platform - Demo

Explain

|

FAQs

How do you switch between tabs in Selenium with Python?

+

Use driver.window_handles to get the available tab handles, then move focus with driver.switch_to.window(handle).

What is the best way to open a new tab in Selenium 4?

+

Use driver.switch_to.new_window('tab'). It is the clearest and most reliable built-in approach in modern Selenium.

How do you return to the previous tab?

+

Store the original handle with driver.current_window_handle, then switch back to it explicitly using driver.switch_to.window(original_tab).

How do you close one tab without closing the whole browser?

+

Use driver.close() to close the active tab only. Use driver.quit() only when you want to end the full session.

Why do tab-switching tests become flaky?

+

The most common causes are switching before the tab exists, relying on a hard-coded tab index, and trying to reuse elements found before the tab change. Waiting properly and re-locating elements after switching solves most issues.

 

Henrik (Minh Huy) Dao
Henrik (Minh Huy) Dao
Senior Quality Engineer
Minh Huy Dao (Henrik) is a Senior Quality Engineer at Katalon, where he has worked since 2023. He has nearly 10 years of experience in QA and test automation, including roles at TMA Solutions, Axon Active and Doctor Anywhere. His work spans automation with Java, JavaScript and WebdriverIO, as well as CI/CD with Jenkins and leading Scrum teams.
Click