An “invalid session id” error in Selenium Python means the browser session your WebDriver object points to no longer exists on the driver process—usually because the browser was closed, crashed, or navigated away from the original session while your script kept a stale driver reference. The fix is almost never a single line of code; it is a discipline: create one session, keep it alive, and if it dies, detect the failure and rebuild the driver instead of reusing the dead object. The most common trigger in practice is an implicit or explicit driver.quit() followed by continued use of driver, or a browser that crashed after a page crash.
The error surfaces as selenium.common.exceptions.InvalidSessionIdException (in Selenium 4) or as a WebDriverException whose message contains “invalid session id.” In both cases the underlying cause is the same: the WebDriver protocol is stateless about lifetime—your Python object is just a handle, and the remote end has forgotten the handle. Treat the exception as “this driver is dead; build a new one,” not “retry the command.”
What the Error Actually Means Under the Hood
When Selenium starts a browser, the driver binary (chromedriver, geckodriver, msedgedriver, or a remote Selenium Grid node) creates a session and returns a session ID such as a3b9c2.... Every subsequent command—get, find_element, click—is a WebDriver protocol request addressed to that session ID.
The session disappears when any of these happens:
You call driver.quit(), which sends DELETE /session/{id} and terminates the browser. The browser process crashes or is killed (out-of-memory, OS kill, manual close of the window in a headed run). A page crash takes down the renderer and, depending on the driver and platform, the session. The remote Grid node dies, times out, or reaps the session under its own idle rules. A driver-binary/browser version mismatch causes the session to be invalidated mid-run rather than at startup.
Once the session is gone, any further command returns an error whose message is “invalid session id.” Your Python driver object still exists—it is just a local wrapper—so calling it again doesn’t recreate anything. That is the key mental model: the object is not the session.
Selenium 4’s exception hierarchy helps: InvalidSessionIdException is a subclass of WebDriverException, so a bare except WebDriverException (without re-checking the message) may swallow unrelated failures such as element-not-interactable. Catch specifically when you want session-specific handling.
Prerequisites Before You Touch the Code
You need a working, non-crashing setup to begin with; fixing session handling won’t help if the browser never starts. Confirm:
Selenium is installed and importable: check pip show selenium and the version. The exception class name and message wording differ between the 3.x and 4.x lines, so note which line you’re on. Your driver binary matches your browser’s major version. A mismatch is a frequent cause of sessions dying early. If you use Selenium Manager (the default in recent Selenium 4 releases), let it resolve the driver; otherwise pin the driver path explicitly and verify it points to the right binary. The browser isn’t being launched headless in a container with no shm space; that setup crashes Chrome tabs routinely, which produces session deaths.
Verify the baseline: run a three-line script that starts the browser, opens about:blank, and quits. If that works once, the problem is lifecycle, not installation.
Step-by-Step: Diagnosing and Fixing the Session
These steps run roughly in order from least invasive to most. They are reversible until the last step.
-
Locate every quit() and close() call, and every place the driver is reused after them. Search the codebase for quit( and close(. A driver.close() closes the current window; if it was the only window, the session ends. A driver.quit() ends everything. Any command after either is the textbook cause. Expected result: you find a path where the script continues past a quit. Check: add a log line right after each quit call, or run in a debugger and confirm control flow stops there.
-
Confirm the session ID is stale rather than the browser being slow. Wrap one command and log the exception’s class and message. If you see InvalidSessionIdException or “invalid session id,” the session is gone; if you see a timeout or “element not interactable,” it’s a different bug and rebuilding won’t fix it. Success check: the error class is explicitly the session one, and the message names a session.
-
Check whether the browser process is still alive. On Linux or macOS, ps aux | grep -i chrome (or firefox) shows whether the browser outlived your commands. On Windows, check Task Manager. If the browser is gone but your script is running, the session died from a crash or quit, not from a network blip. Expected result: no browser process, or a browser process with a different, newer profile than the one you think you have.
-
Look at the driver log for the session teardown. Enable the driver’s verbose log (chromedriver accepts --log-path and --verbose; Selenium 4 can pass service arguments) and read the sequence. You are looking for a DELETE /session/... call (an explicit quit) versus a process exit or crash line. This distinguishes “your code quit it” from “the browser died on its own.” Success is being able to say which one happened from the log line, not from guessing.
-
If the cause is a browser crash, fix the crash before the lifecycle. Common culprits on CI: Chrome in a container with /dev/shm smaller than the page’s memory needs (fix with --disable-dev-shm-usage and adequate --shm-size), a very old driver/browser pair, or a GPU-related sandbox crash in headless mode. Expected result: repeated single runs stop crashing. Check: run the same workload five times unattended and confirm zero session deaths without code that retries.
-
Introduce a single owner for the driver lifecycle. Structure the script so exactly one function creates the driver, hands it to the work, and quits it in a finally block. Nothing else calls quit. This eliminates the most common human cause: a helper or exception handler closing the browser while the main path is still using it. Expected result: on a normal run, one start and one quit in the log.
-
For anything that can crash, make the driver rebuildable rather than resilient in place. A dead session cannot be revived; write a small factory that returns a new driver, and on InvalidSessionIdException (or a session-death WebDriverException), discard the old object and call the factory again inside a bounded retry loop. See the next section for the shape of that code. Success check: after you kill the browser mid-run (or trip a deliberate crash), the script logs a rebuild and completes the step instead of raising.
-
If you use Selenium Grid or a remote command_executor, check the node’s session timeout. Nodes reap idle sessions. Long waits between commands—sleeps, slow downloads, reading huge pages—can outlast the node’s configuration. Expected result: the log shows the node closing the session, not the browser. Check: reduce idle time or raise the node’s timeout, then rerun the same wait.
Stop condition: if the browser reliably crashes during startup or on a specific page even after version alignment and container flags, that is a browser/driver/environment defect, not a session-handling problem. At that point, gather the driver log and browser crash dump and escalate to whoever owns the environment rather than layering more retries.
The Minimal Correct Lifecycle Pattern
Here is the essential shape. It uses try/finally for cleanup and a factory so a dead session can be replaced. Inputs are your driver options and a target URL; the illustrative waits are placeholder numbers, not tuned values.
Two details matter. First, quit() on an already-dead session can itself throw, so the final cleanup swallows that specific failure; that is safe because there is nothing left to close. Second, the rebuild replaces the local driver variable, but any helper that captured the old driver still holds a dead handle—so pass the driver explicitly into helpers instead of storing it in a module global.
This pattern does not make work idempotent. If the session died after a form submit or a payment click, re-running from the top can duplicate the action. For destructive steps, record a checkpoint (e.g., “submitted”) and resume from it after rebuild rather than replaying everything.
Common False Fixes and Why They Fail
Adding time.sleep is the most common non-fix. A pause does nothing for a session that no longer exists; it only changes timing for other diseases (flaky element readiness), which is a different error. If your script suddenly “works” after adding a sleep, the original failure was almost certainly a race on element loading, not a session death—check whether the exception was ever actually the session one.
Reusing one global driver across test methods is another source. A test runner that quits the driver at the end of one test but leaves the global pointing at it will produce invalid-session errors at the start of the next. The fix is per-test ownership (a fixture that creates and quits), or a module-level driver that the runner never closes until teardown.
“Catch the exception and continue” is another false fix. If the session is gone, every subsequent command fails the same way; you’ve just converted one clear error into a cascade. The only valid response to invalid session is replacement, not suppression.
Finally, “just restart the whole script.” That works operationally but hides the root cause. Use the log from step 4 to determine whether the script or the browser caused the death; restarting on top of an unexplained crash will recur.
Environment-Specific Cases
Docker and CI containers: Chrome’s default use of /dev/shm causes tab crashes when the container has the default 64 MB. The flag --disable-dev-shm-usage plus a larger --shm-size at container creation usually eliminates these crashes. This is a browser stability fix that prevents sessions from dying, not a session-handling fix per se, but it shows up as invalid session because the log may not distinguish a crash from a quit.
Selenium Grid (remote command_executor): your session lives on a node. Node cleanup, container restarts under orchestration, and idle timeouts all appear locally as invalid session. Remote sessions are especially prone to non-idempotent work, so checkpointing matters more. Check the Grid node’s session timeout configuration and whether capability negotiation could be starting against a different node than you think.
Headless browser crashes: headless mode can surface crashes that headed mode hides. If the headed version never dies but headless dies routinely, the underlying browser is crashing; look at the driver log for the crash line and treat it as a browser defect, not a Selenium lifecycle issue.
Windows with a rapid-fire run: closing the browser window manually during a headed run ends the session. If scripts rely on the browser staying open between steps for humans to observe, that is the trigger; use a fresh driver per run or don’t quit until the observation window is over.
Edge Cases and Failure Modes That Still Bite
Multiple windows: driver.close() on the last remaining window ends the session even without quit(). If you close tabs, verify that at least one window remains before continuing, or switch to the surviving handle first.
Driver process death: if the driver binary is killed (not the browser), the session is unreachable and invalid-session is the symptom. Explicitly record the driver’s process termination. On Linux you can use ps against the driver’s executable; on the code side, driver.service in Selenium 4 exposes the service handle so you can inspect its state in debugging.
Timeouts versus invalid session: a very long page load can produce TimeoutException, not invalid session; if you see invalid session after a timeout, the browser itself probably crashed under the load, so fix the page or resource limits. Do not conflate the two exceptions when triaging.
Multiple webdriver.Chrome() instances in one process: two live sessions with the same user-data directory can corrupt or mutually break profiles. Give each session its own profile directory if you deliberately run parallel browsers.
A stale test harness: some CI harnesses run the script twice; the first instance quits the browser, the second tries to reuse a session ID passed through the environment. Treat session IDs as per-process only; never persist and reuse them across runs.
A Reasonable Operational Policy
For most Python automation scripts, the durable policy has three parts. Create exactly one driver per logical run, from a single factory, and quit it exactly once in finally. Detect invalid session specifically and replace the driver with bounded retries, never trying to “continue” on the dead object. And when invalid session appears in production logs, treat it as a crash/timing signal to investigate in the environment (container shm, version match, browser crash logs) rather than as a trigger to add more retries.
Two useful numbers, labeled as examples rather than measured guarantees: a couple of rebuild attempts (2–3) covers transient crashes without masking systematic ones; and when you observe the failure, record the exact exception class and message and the driver log line so the crash-versus-quit distinction is auditable. If the driver log is unavailable, that is the first gap to close—it is the fastest path from a symptom to a cause here.