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

Save the current window handle, trigger the new tab or window, wait until WebDriver can see it, then switch to its handle with driver.switch_to.window(handle). When you finish, close the extra context if needed and switch back to a handle that is still open.

How Selenium identifies windows and tabs

WebDriver selects a browser tab or window by its window handle, not by whichever page appears to have visual focus. A tab and a separate browser window are both browsing contexts for this purpose. Before interacting with a newly opened context, explicitly switch WebDriver to its handle.

The dependable sequence is to record the existing handle or handles, perform the action that opens another context, wait for it to appear, identify the new handle, and switch to it. Avoid relying on a fixed handle index: handle ordering should not be used as a durable way to identify a particular page.

Switch to a window opened by a page action

This example follows Selenium’s documented window-switching workflow. The link opens another context; an explicit wait prevents a race between the click and the new handle becoming available.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
LAPGEAR Home Office Pro Lap Desk - Black Carbon, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 14.1" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy ergonomic support with the integrated cushioned wrist rest.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a sleek black carbon color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.8 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

url = "https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html"
driver = webdriver.Chrome()

try:
    driver.get(url)
    wait = WebDriverWait(driver, 10)
    original_window = driver.current_window_handle

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

    new_window = (set(driver.window_handles) - {original_window}).pop()
    driver.switch_to.window(new_window)

    # WebDriver commands now target the new tab or window.
    print(driver.title)

    driver.close()
    driver.switch_to.window(original_window)
finally:
    driver.quit()

The set difference finds a handle that was not present before the click. This concise form assumes the session had exactly one window beforehand and the page opened exactly one more. If several contexts may be opened, compare the complete before-and-after handle sets, as shown below.

When the final window count is not known

Use EC.new_window_is_opened(previous_handles) to wait for the number of handles to increase rather than requiring a specific total. Save the original set before triggering the action and inspect the difference afterward:

Rank #2
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
before = set(driver.window_handles)
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.new_window_is_opened(list(before)))

added_handles = set(driver.window_handles) - before
if not added_handles:
    raise RuntimeError("No new window handle appeared")

new_window = added_handles.pop()
driver.switch_to.window(new_window)

If an action can open more than one context and you need to handle all of them, retain the full added_handles set rather than popping just one. The expected-conditions API documents both number_of_windows_to_be(num_windows) and new_window_is_opened(previous_handles): Selenium Python expected conditions.

Create a tab or window directly with Selenium 4+

If the test itself—not a website action—needs a new blank context, Selenium 4 and later provide driver.switch_to.new_window(...). It creates and focuses the requested context, so there is no additional switch immediately afterward.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Yilador Webcam Cover 3 Pack, 0.03 inch Ultra Thin Laptop Camera Cover Slide
  • Note: Not suitable for MacBooks released after 2023 or devices with a protruding front camera; Not applicable to full-screen or notch-style tempered glass screen protectors; Do not use on the rear camera of the phone.
  • 💻 Why Do You Need a Webcam Cover Slide? — Safeguard your privacy by covering your webcam with our reliable webcam cover when not in use. Don't let anyone secretly watch you. Stay protected!
  • ✅ Thin & Stylish — Enhance your laptop's functionality and aesthetics with our 0.027" ultra-thin webcam covers. Seamlessly close your laptop while adding a touch of sophistication.
  • ✅ Fits Most Devices — Compatible with laptops, phones, tablets, desktops! Keep your privacy intact on Ap/ple, Mac/Book, iPh/one, iP/ad, H/P, L/novo, De/ll, Ac/er, As/us, Sa/msung devices.
  • ✅ 365 Days Protection — Our upgraded 3.0 adhesive ensures a strong hold that won't damage your equipment. Experience reliable, long-term privacy protection day in and day out.
from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    original_window = driver.current_window_handle

    driver.switch_to.new_window("tab")
    driver.get("https://www.selenium.dev")
    print(driver.title)

    driver.close()
    driver.switch_to.window(original_window)
finally:
    driver.quit()

Use "tab" for a new tab or "window" for a separate window. The key difference from a site-triggered context is that the Selenium API creates and selects it directly; a site-triggered context must be detected with a wait before switching. See the official Selenium windows and tabs guide.

Close a context and return safely

driver.close() closes only the currently selected tab or window. It does not end the whole WebDriver session, nor should you assume it automatically selects another context. Switch to a saved handle that remains open before issuing more browser commands. Selenium warns that failing to switch after closing a window can leave WebDriver on a closed page and cause a No Such Window Exception in its window-switching guide.

Rank #4
AboveTEK Portable Laptop Lap Desk w/Retractable Left/Right Mouse Pad Tray, Non-Slip Heat Shield Tablet Notebook Computer Stand Table w/Sturdy Stable Work Surface for Bed Sofa Couch or Travel
  • Anti-Slip Surface - Transform your laptop into a mobile workstation with the AboveTEK portable laptop lap desk. The anti-slip surface provides a strong grip for laptops up to 15.6 inches(Diagonal), while the double rubber strip on the bottom ensures a stable display or typing experience on your lap, couch, or bed.
  • Retractable Mouse Pad - Retractable laptop mouse pad extends on both directions for the left/right handed with elevation along the edges for stopping mouse from falling off. The size of laptop tray is 14" X 9.7" and the size of mouse pad is 7.4" X 6.1".
  • Effective Heat Shield - The effective heat shield made of sturdy and thick material protects your laptop from overheating. Prioritizes your comfort and safety, an ideal lap pad or board for working anywhere.
  • EASY to Carry and Store - With an ergonomic and simplistic design, the lap desk is portable to store in a backpack. Only 15" in size, 2.2 lb of weight and with slim 0.6 inch thickness, it is ready to be easily carried around.
  • Widely Applicable - The smooth platform accommodates laptops and tablets up to 15.6 inches(Diagonal), making it a versatile accessory and one of the best gifts for mom, dad, students and professionals. Perfect for use as a laptop bed tray or tablet holder anywhere at home, library, or park.

Use driver.quit() when the test is finished; it ends the session and closes all its windows. Put it in a finally block so cleanup still runs if an assertion or interaction fails. If code needs to continue after closing one context, switch to a known live handle first.

Common errors and fixes

  • The new handle is missing immediately after clicking: the page may not have opened the context yet. Wait with EC.number_of_windows_to_be(...) when the target count is known, or EC.new_window_is_opened(...) when it is not. Avoid using a fixed sleep as the main synchronization method.
  • WebDriver interacts with the original page: visual focus does not select a WebDriver context. Find the newly added handle and call driver.switch_to.window(new_window).
  • The wrong handle is selected: do not assume a permanent index in driver.window_handles. Compare handles before and after the action. With multiple existing contexts, use the complete before-and-after sets.
  • No Such Window Exception after closing a page: the selected handle may refer to the context just closed. Switch to a remaining, valid handle before continuing.
  • A frame switch does not reach another tab: frames and windows are different browsing-context operations. Use Selenium’s frame-switching API for a frame; use switch_to.window(handle) for another tab or window.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean screenshot rather than browser automation, ScreenshotNeo can return an image or PDF from one GET request. Its API accepts a URL and can return PNG, JPEG, WebP, or PDF. The API’s cookie-banner handling and cleanup options are intended for screenshots; they do not replace Selenium when you need to click through a workflow or test application behavior.

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

Install the Python dependency with python -m pip install requests, then run this example with a ScreenshotNeo API key:

Best Value
Sale
LAPGEAR Home Office Lap Desk – Pink, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 12" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy laptop support with the integrated device ledge.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a blush pink color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.14 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
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)

See the ScreenshotNeo API documentation for request options. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

FAQ

Does opening a new tab automatically switch Selenium to it?

Not when a page action opens it. Wait for its handle and explicitly switch. The Selenium 4+ new_window("tab") API is the exception: it creates and focuses the new tab itself.

What is the difference between close() and quit()?

close() closes the selected context; quit() ends the WebDriver session and closes all its windows.

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

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.