Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

How to Handle Browser Tabs in Selenium (Python)

Use Selenium window handles to wait for, identify, and switch between browser tabs, then return safely to an open context.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Selenium, tabs and windows use the same model: each is a browsing context with its own window handle. Save the current handle, wait for a newly opened context, find its handle, and switch to it before interacting with the page. The examples below use Python; Selenium 4 and later can also create and switch to a new tab or window directly.

How Selenium identifies tabs and windows

Selenium’s WebDriver does not distinguish between browser tabs and windows for this workflow. Each open browsing context has a handle. The handle is the value you use to tell WebDriver which context should receive commands. A tab becoming visually active in the browser does not automatically switch WebDriver to it.

The core workflow is: save the original handle, trigger the action, wait for the context to appear, identify its handle, and switch to it. Selenium documents this behavior in its Working with windows and tabs guide.

Switch to a tab opened by a click

Use an explicit wait rather than assuming the new tab appears immediately. This complete example assumes the driver and wait are already initialized and that the page contains a link whose visible text is “Open new window.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

original_handle = driver.current_window_handle

 driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))

new_handle = (set(driver.window_handles) - {original_handle}).pop()
driver.switch_to.window(new_handle)

wait.until(EC.title_is("Expected page title"))

Remove the accidental leading space before driver.find_element if copying this code; the runnable version is:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

original_handle = driver.current_window_handle

driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))

new_handle = (set(driver.window_handles) - {original_handle}).pop()
driver.switch_to.window(new_handle)

wait.until(EC.title_is("Expected page title"))

Set the expected count to match your test. If there are already multiple open contexts or the click can open more than one, wait for the handle set to grow and select from the difference rather than assuming there will be exactly two. Then check a distinguishing page property, such as the title or URL, if more than one new context is possible. The Python APIs for handles and expected conditions are documented in the WebDriver API reference and expected conditions reference.

Create a new tab or window with Selenium 4+

If the test needs a blank browsing context rather than one opened by the site, Selenium 4 and later provide a direct API. It creates the requested context and switches WebDriver to it.

driver.switch_to.new_window("tab")
# Or:
driver.switch_to.new_window("window")

Use the installed binding’s documentation if your project targets an older Selenium release or a specific version, since the direct creation API is documented for Selenium 4 and later.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Return to the original tab and close contexts safely

Keep the original handle so you can explicitly return to it. Closing a context does not restore the previous one for you.

driver.close()  # closes the current tab or window
 driver.switch_to.window(original_handle)

As above, remove the leading space before driver.switch_to when copying; use this runnable form:

driver.close()
driver.switch_to.window(original_handle)

Only switch to a handle that is still open. driver.close() closes the current context; driver.quit() ends the WebDriver session and closes all its windows.

Handle multiple new tabs without relying on their order

A fixed index such as driver.window_handles[1] can select the wrong context if the set of open tabs changes. Compare the current handles with the handle saved before the action instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
handles_before = set(driver.window_handles)
# Trigger the action that may open a context.
wait.until(lambda d: len(set(d.window_handles) - handles_before) > 0)
new_handles = set(driver.window_handles) - handles_before

for handle in new_handles:
    driver.switch_to.window(handle)
    if driver.title == "Expected page title":
        break
else:
    raise AssertionError("Expected page did not open")

If several contexts may appear, identify the intended one using a page-specific condition after switching. Do not assume handle order indicates which tab is newest or which page you want.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting tab-switching failures

  • The click seems to open a tab, but commands still affect the old page: switch explicitly with driver.switch_to.window(handle). Browser focus and WebDriver’s selected context are separate.
  • The new handle is missing: wait for the expected handle count or for the handle set to grow. Confirm that the site action actually opened a new context and that the expected count fits the test’s initial state.
  • The script switches to the wrong tab: avoid a fixed list index. Use the difference between the handles before and after the action, then confirm the page by title or another distinguishing property.
  • NoSuchWindowException occurs after closing a tab: the driver may still be targeting the closed context. Switch to a handle that remains open before sending another command.
  • The title check fails immediately after switching: the new document may not have finished loading. Wait for the expected title or another relevant page condition instead of querying too early.

Or skip the browser setup

If you need a screenshot rather than browser interactions, ScreenshotNeo can return a screenshot from one GET request. Its API removes supported cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed; it also provides an MCP server for AI agents.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for request options. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.