Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →To handle multiple windows or tabs in Selenium, save the current window handle, trigger the new context, wait until WebDriver reports it, switch to its handle, and switch back to a still-open handle after closing it. A browser tab and a separate window are both selected through WebDriver window handles.
How Selenium identifies windows and tabs
WebDriver commands apply to the currently selected browsing context. Opening a tab or window in the browser does not, by itself, guarantee that your next Selenium command is aimed at the new context: explicitly call driver.switch_to.window(handle). Handles are session-specific identifiers; do not assume a fixed list position will always identify the context you want.
The examples below follow Selenium’s official window interactions guide and its Python expected-conditions reference.
Switch to a window opened by a site action
Save the original handle before clicking, wait for the window count to change, then find the handle that was added. This complete example uses the Selenium guide’s page and link text:
Recommended Free Tools
#1 Best Overall
- 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
handles_before = set(driver.window_handles)
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(len(handles_before) + 1))
added_handles = set(driver.window_handles) - handles_before
if len(added_handles) != 1:
raise RuntimeError(f"Expected one new window; found {len(added_handles)}")
new_window = added_handles.pop()
driver.switch_to.window(new_window)
# Interact with the newly selected page here.
driver.close()
driver.switch_to.window(original_window)
finally:
driver.quit()
If the session began with exactly one window, the common shorter form is new_window = (set(driver.window_handles) - {original_window}).pop() after waiting for a count of two. The set-difference approach also works when there were multiple contexts before the action, provided you compare the before and after sets.
Wait for the new context instead of guessing timing
A click may return before the browser has exposed its new window handle. Use an explicit wait before reading handles and switching. Selenium provides two useful expected conditions:
Rank #2
- 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.
EC.number_of_windows_to_be(n)waits until the total number of windows equalsn. Use it when you know the expected total.EC.new_window_is_opened(previous_handles)waits for the handle count to increase. Use it when you only need to know that at least one new context appeared.
For example, when you do not know the precise count beforehand:
handles_before = driver.window_handles
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.new_window_is_opened(handles_before))
new_handles = set(driver.window_handles) - set(handles_before)
new_window = new_handles.pop()
driver.switch_to.window(new_window)
If a site can open more than one context in response to the action, inspect all added handles rather than popping an arbitrary one; identify the intended page using an appropriate page property, such as its title or URL.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #3
- 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.
Create a tab or window directly in Selenium 4+
When the test itself needs a fresh browsing context rather than one opened by the site, Selenium 4 and later provide driver.switch_to.new_window(). The call creates and focuses the requested context, so an immediate extra switch is unnecessary.
# Create and select a new tab
driver.switch_to.new_window("tab")
# Or create and select a separate browser window
driver.switch_to.new_window("window")
Use the site-action workflow when you are testing a link, popup, or other behavior that opens a context. Use new_window when the test needs to create a blank context itself.
Rank #4
- 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.
Close a context and return safely
driver.close() closes the currently selected window or tab. It does not end the entire WebDriver session or automatically select another surviving context. Switch to a handle that is still open before issuing further commands. driver.quit() ends the session and closes all of its windows, which is why the example calls it in a finally block.
Selenium warns that failing to switch away after closing a window can leave WebDriver pointed at a closed page and cause a No Such Window Exception. If the original context might have been closed, select another handle from the current driver.window_handles list rather than trying to reuse a stale handle.
Best Value
- 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.
Common problems and fixes
- Switching too early: The new context is not in
driver.window_handlesyet. Wait withEC.number_of_windows_to_beorEC.new_window_is_opened, then retrieve the handles. - Choosing a handle by index: An index is not a reliable way to identify the context opened by the latest action. Compare handle sets before and after the action.
- Commands still target the old page: WebDriver’s selected context has not changed. Call
driver.switch_to.window(new_window)before interacting with the new page. No Such Window Exceptionafter closing: The selected context was closed and no live context was selected afterward. Switch to a remaining handle, or end the session withdriver.quit().- Trying to switch into a frame with a window handle: Frames and windows are different browsing-context operations. Use Selenium’s frame-switching APIs for frames; use window handles for tabs and windows.
- The handle set grows by more than one: The action opened multiple contexts or another context appeared concurrently. Inspect the added handles and choose the intended one instead of assuming there is exactly one.
Or skip the browser setup
If you need a screenshot rather than an interactive Selenium session, ScreenshotNeo can return an image or PDF from one GET request. Cookie banners are accepted and removed, along with known newsletter popups and chat widgets, before capture; these steps can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers indicating the page verdict and billing status. ScreenshotNeo also offers an MCP server for AI agents, including Claude and Cursor.
For example, save a screenshot of Stripe as WebP:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for request options. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
Frequently Asked Questions
Does switching to a new tab require a different Selenium API than switching to a window?
No. Both are selected with driver.switch_to.window(handle); Selenium 4+’s new_window("tab") and new_window("window") specify which type to create.
Are window handles stable across WebDriver sessions?
No. Treat handles as identifiers for contexts in the current session, not permanent identifiers to save and reuse across sessions.
Quick Recap
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.




