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.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

The fix is to stop using the ended WebDriver instance and create a new session. Selenium reports an “unknown session id” (usually exposed in Python as InvalidSessionIdException) when the remote WebDriver end no longer lists that session as active. Find the code that ended the session—often quit() in teardown or a helper—then move later commands to a newly created driver. Do not try to revive or retry commands with the old session ID.

What “unknown session id” actually means

A WebDriver session is the server-side relationship between your client code, the browser, and the driver or Grid node. Creating a driver creates that session. Every later command carries its session identifier. The remote end rejects a command when that identifier is no longer in its active-session list.

In Selenium’s Python binding, the protocol error is mapped to InvalidSessionIdException, defined as an exception thrown when the given session ID is not in the list of active sessions. “Unknown SessionId,” “invalid session id,” and similar wording describe the same state problem; the exact capitalization depends on the binding and remote server.

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

The message alone does not prove why the session disappeared. Your code may have called quit(), a fixture may have cleaned up earlier than expected, or a remote browser process may no longer be available. Diagnose the lifecycle first rather than assuming a particular browser, timeout, or version defect.

First response: locate the session-ending operation

  1. Search backward from the failing command. Inspect the test, fixture, teardown hook, helper, and exception path for driver.quit() or another shutdown routine.
  2. Check object ownership. Confirm that a helper did not receive the driver, quit it, and return control to code that still plans to use it.
  3. Check control flow after cleanup. A command in a finally block, callback, or failure handler can run after the normal teardown has already ended the session.
  4. Check parallel and Grid coordination. Another worker or fixture must not clean up a driver that this test still owns.
  5. Restart the session, not the identifier. Instantiate a new driver and use that object for subsequent commands.

Log the point where the driver is created and where cleanup runs. A short lifecycle log is usually more useful than repeatedly rerunning the same stale object.

close() versus quit()

Method Scope Can automation continue? Use it when
close() Closes the current browser window. Possibly, if another valid window remains and you switch to it. You intentionally finish one window while continuing the same session.
quit() Ends the entire WebDriver session and closes its associated windows and processes. No. The driver instance must not receive further commands. Final cleanup, test teardown, or releasing a Grid allocation.

Calling close() is not a substitute for final cleanup. Conversely, calling quit() and then navigating, finding elements, or switching windows through that object is a direct route to an invalid session error. Selenium recommends ending a session with quit(); on Grid, it also tells the Grid that the browser is no longer in use.

Correct Python patterns

Use try/finally for explicit ownership

from selenium import webdriver


driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    print(driver.title)
finally:
    # Last WebDriver command in this session.
    driver.quit()

Nothing that uses driver should appear after the finally block. If an assertion or navigation is needed after cleanup, perform it before quit(), or create a separate session.

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

Use Selenium’s Python context manager

from selenium import webdriver

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    print(driver.title)
# The context exits by quitting the session. Do not use driver here.

This keeps teardown tied to a clear scope. Pass data out of the block rather than passing the ended driver object onward.

Create a new session after an ended one

from selenium import webdriver

old_driver = webdriver.Chrome()
old_driver.get("https://example.com")
old_driver.quit()

# A new object creates a new active session.
new_driver = webdriver.Chrome()
try:
    new_driver.get("https://www.selenium.dev")
    print(new_driver.title)
finally:
    new_driver.quit()

The important detail is that new_driver represents a new session. Assigning the old object to another variable, catching the exception and retrying, or manually reusing its session ID does not repair the server-side state.

Fixture design: keep setup and teardown in one scope

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    instance = webdriver.Chrome()
    try:
        yield instance
    finally:
        instance.quit()

def test_homepage(driver):
    driver.get("https://example.com")
    assert driver.title

Do not call quit() inside test_homepage when the fixture owns cleanup. If a test needs a second browser, request or construct a separate fixture with separate ownership.

Window closure is a different diagnostic path

A session can remain active while one of its windows is closed. If your code closes a tab and then tries to use the closed window, Selenium’s window guidance points to a “no such window” failure, especially when code forgot to switch back to another handle. That is different from an invalid session ID.

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

Likewise, a stale element reference concerns an element object that is no longer valid in the current document. It is not evidence that the whole WebDriver session disappeared. Read the exception class and message before changing teardown code.

Grid and remote-driver checks

With Selenium Grid or another remote endpoint, inspect the test framework’s allocation and release lifecycle. A fixture, retry wrapper, or worker may have called quit() and returned the slot while later code retained the old driver reference. Ensure that each test owns exactly one cleanup path and that a driver is not shared across workers unless the framework explicitly supports that design.

When a remote session vanishes without an obvious quit(), preserve the complete client and server logs and correlate timestamps. The error establishes that the session is no longer active; it does not, by itself, identify whether the browser process, driver service, node, or test code ended it.

Common symptoms, causes, and fixes

Symptom Likely lifecycle mistake Fix
Failure immediately after a helper returns The helper quit a driver it did not own. Move cleanup to the owner or return results instead of the driver.
Failure only during teardown A teardown hook runs twice, or code issues a command after the first cleanup. Make teardown idempotent in structure: one owner, one quit(), and no post-cleanup commands.
Failure after switching tabs The current window was closed and no valid handle was selected. Switch to a remaining handle; if the message is a window error, debug handles rather than session IDs.
Failure after a test retry The retry reused an object from the failed attempt. Create a fresh driver for every attempt and clean it up in that attempt’s scope.
Failure on Selenium Grid The session was released before a later command. Trace allocation, quit(), and worker boundaries; never share a released driver.
Failure after catching an exception Error handling quit the driver, then the recovery path reused it. Either finish after cleanup or construct a new driver before recovery.

A reliable recovery checklist

  • Record the exact exception type and the command that failed.
  • Find every quit() and close() reachable before that command.
  • Identify the single owner responsible for cleanup.
  • Remove commands that run after quit().
  • Use close() only for intentional current-window management.
  • Create a new driver for a new session; do not retry the old session ID.
  • For Grid, correlate client, node, and test-runner lifecycle logs.
  • Reclassify the problem if the actual exception is stale-element or no-such-window.

Performance, reliability, and cost considerations

Starting a new browser session is more expensive than issuing another command, so avoid accidental session churn by scoping one driver to a test or controlled fixture. Reusing a session is safe only while it remains active and its state is intentionally owned. Reusing an object after cleanup is not an optimization; it is invalid state.

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

For reliable cleanup, keep the final quit() in a guaranteed path and capture diagnostics before it runs. If a failure requires a fresh session, preserve the original exception and start the replacement explicitly so the test report shows both the cause and the recovery.

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 simply to obtain a page image rather than drive an interactive Selenium session, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also offers an MCP server for AI agents, including Claude, Cursor, and other MCP clients.

See the full parameter list in the ScreenshotNeo documentation. The following call captures a WebP image:

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

The service includes full-page and element captures, device presets, arbitrary viewports, retina scale, PDF output, HTML/CSS rendering, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Common parameter names used by other screenshot APIs also work.

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

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Create a free ScreenshotNeo account to get started.

FAQ

Can I reset the session ID manually?

No. The remote end controls which sessions are active. Start a new WebDriver instance instead.

Should I call close() or quit() in a test?

Use close() for deliberate current-window management and quit() for final session cleanup.

Does this exception always mean the browser crashed?

No. It proves only that the identifier is not active. Inspect code ownership, teardown, and remote logs before assigning a cause.

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

Frequently Asked Questions

Can I reset the session ID manually?

No. The remote end controls active sessions; instantiate a new WebDriver to obtain a new session.

Should I call close() or quit() in a test?

Use close() for deliberate current-window management and quit() for final session cleanup.

Does this exception always mean the browser crashed?

No. It proves only that the identifier is inactive; inspect teardown and remote lifecycle logs for the cause.

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.

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.