ScreenshotNeo

BlogGuides

49 Common Selenium Exceptions and How to Fix Them

Diagnose 49 Selenium Python exceptions by failure layer, then fix waits, locators, browser context, interactions, sessions, and driver setup.

By the ScreenshotNeo team4 October 202614 min read

Selenium exceptions are signals about what failed: page state, a locator, a DOM reference, an interaction, or the browser session. Start by identifying that layer, then verify the page and context before changing code. Selenium says poor synchronization is its most common error cause, but longer waits are not a universal fix. This guide names 49 exception classes from the Selenium Python 4.50.0 API; other language bindings may expose different inventories.

The direct fix is usually to verify the current page and browsing context, confirm the locator against the live DOM, wait for the specific state the action needs, and reacquire elements after DOM changes. For session errors, check browser and driver startup instead of changing page selectors. The official [Selenium troubleshooting guide](https://www.selenium.dev/documentation/webdriver/troubleshooting/) recommends this diagnostic approach.

Diagnose the failure layer first

  1. State and timing: Did navigation finish, and is the expected content present? Check this for missing elements and timeouts.
  2. Locator: Does the selector match the current DOM, and does its syntax match the selected strategy?
  3. DOM lifecycle and context: Was the element replaced? Did the script navigate or switch frames or windows?
  4. Interactability: Is the target displayed, enabled, in view, and unobstructed where Selenium clicks it?
  5. Session and environment: Is the WebDriver session alive, and can the browser and driver start in this environment?

For a screenshot or visual inspection of a page during debugging, Selenium is not the only option. ScreenshotNeo is a website screenshot API and MCP server by Yorker Media: a single GET request returns an image or PDF. It can help capture a page without starting a local WebDriver session; it does not replace Selenium when you need to interact with or test the page. See ScreenshotNeo.

Run a minimal diagnostic before changing the test

This Python example uses explicit waits, checks the current URL and title, and reports the screenshot and page source when the expected element does not appear. It assumes Selenium Python is installed and a supported browser is available. Selenium Manager can locate a driver in supported setups; otherwise configure the browser driver as described in Selenium’s driver troubleshooting documentation.

from pathlib import Path
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
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://example.com"
locator = (By.CSS_SELECTOR, "h1")
driver = webdriver.Chrome()

try:
    driver.get(url)
    print("URL:", driver.current_url)
    print("Title:", driver.title)

    try:
        heading = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located(locator)
        )
        print("Found:", heading.text)
    except TimeoutException:
        Path("failure.png").write_bytes(driver.get_screenshot_as_png())
        Path("failure.html").write_text(driver.page_source, encoding="utf-8")
        raise
finally:
    driver.quit()

Use the condition that matches the next action: presence for DOM existence, visibility before reading visible text, and clickability before clicking. A clickability wait checks visibility and enabled state; it cannot guarantee that an overlay will not move over the element immediately afterward.

The 49 exceptions, grouped by what failed

The names below are from the Selenium Python 4.50.0 exception reference. The description and likely remedy are practical summaries, not a claim that every binding uses the same exception type. Selenium’s [common errors guide](https://www.selenium.dev/documentation/webdriver/troubleshooting/errors/) covers several of these in more depth.

1. Locator and page-state failures

Exception What it indicates Verify and fix
NoSuchElementException The search found no matching element at that moment. Confirm the page and preceding navigation succeeded; inspect the live DOM and selector. If the element appears asynchronously, wait for its relevant condition.
InvalidSelectorException The selector is malformed or paired with the wrong strategy. Check CSS versus XPath versus ID syntax and validate the selector against the DOM.
TimeoutException A wait condition did not become true before its deadline. Log the URL, title, screenshot, and page source. Determine whether the page is wrong, the target is absent, or the wait condition is unsuitable before increasing the deadline.
ElementNotSelectableException The requested selection operation is not valid for this element. Check whether the locator targets an option or another selectable control; use the appropriate interaction for the actual element.

2. DOM lifecycle and browsing-context failures

Exception What it indicates Verify and fix
StaleElementReferenceException A previously located element reference is no longer accessible, commonly after a refresh, navigation, DOM rebuild, or context change. Reacquire the element after the update. If a frame or window changed, switch to the intended context first. Do not keep retrying operations on the old reference.
NoSuchFrameException The requested frame was not found. Verify the frame locator and whether it has loaded; wait for the frame when asynchronous, then switch into it.
NoSuchWindowException The requested window handle is unavailable. Inspect current handles after opening or closing windows, then switch using a live handle.
NoSuchShadowRootException The element has no accessible shadow root at the point queried. Confirm the host and page state, then access the shadow root only where the component actually uses shadow DOM.
DetachedShadowRootException A previously obtained shadow root is detached from the document. Reacquire the host and its shadow root after component or page updates.
DetachedShadowRootException A stored shadow-root reference no longer belongs to the current DOM. Find the current host again and obtain a fresh shadow root.

3. Element interaction failures

Exception What it indicates Verify and fix
ElementClickInterceptedException Another element would receive the click at the target’s center. Check overlays, dialogs, sticky headers, and animations. Wait for the obstruction to end and position the control so its center is clear. Selenium’s [interaction guide](https://www.selenium.dev/documentation/webdriver/elements/interactions/) explains center-based click targeting.
ElementNotInteractableException The requested action cannot be performed in the element’s current state. Confirm the locator targets the actual control, and that it is displayed, enabled, in view, and supports the operation.
InvalidElementStateException The operation conflicts with the element’s current state. Inspect visibility, enabled/read-only state, and whether the action fits this element. Wait for an expected state transition if one is in progress.
MoveTargetOutOfBoundsException A pointer move targets coordinates outside the viewport or valid element bounds. Check the element position and viewport size; scroll it into view and use a valid pointer target.
ScreenshotException The browser could not produce the requested screenshot. Check browser/session health and screenshot dimensions or target support; retry only after correcting the cause.

4. Session and command failures

Exception What it indicates Verify and fix
InvalidSessionIdException A command was sent to a session that no longer exists, often after quit() or closing the last tab. Review teardown and test lifecycle; do not send commands after session shutdown.
SessionNotCreatedException The browser session could not be started. Check browser/driver compatibility, binary path and permissions, and operating-system or container restrictions.
NoSuchDriverException The required browser driver could not be located or started. Confirm the browser is installed and accessible; use Selenium Manager or configure the binding’s Service path. See [Unable to Locate Driver](https://www.selenium.dev/documentation/webdriver/troubleshooting/errors/driver_location/).
WebDriverException A general WebDriver operation failed; this may originate in the browser driver. Read the full driver message and logs, reproduce in another browser to isolate driver-specific behavior, and reduce to the failing command.
UnsupportedCommandException The remote end does not support the requested command. Check browser, driver, and Selenium versions and whether the command is supported in that combination.
UnknownMethodException The remote end does not recognize the command method. Check client/driver compatibility and endpoint configuration.
InvalidArgumentException A command parameter is invalid. Check argument types, ranges, required fields, and the API method signature.
InvalidCoordinatesException Coordinates supplied to a command are invalid for the target or viewport. Recalculate from the current viewport and element geometry; avoid reusing coordinates after layout changes.
InvalidCookieDomainException A cookie is being set for a domain that does not match the current page. Navigate to the intended domain before adding the cookie and verify the cookie domain rules.
UnableToSetCookieException The browser rejected the cookie operation. Check domain, path, secure/same-site attributes, and whether the current page context allows the cookie.
UnableToCaptureScreenException The remote end cannot capture the screen for the requested command. Check session status and browser support, then capture a simpler target to isolate the issue.
InsecureCertificateException A certificate problem prevents the requested navigation or operation. Inspect the certificate and environment. Use an appropriate test certificate or controlled browser configuration rather than suppressing certificate checks indiscriminately.
UnexpectedAlertPresentException An unexpected alert blocks the command. Check whether the page raised an alert; accept or dismiss it deliberately before continuing.
AlertNotPresentException The script attempted to use an alert that is not present. Wait for the alert only if the page should open one; otherwise remove the alert handling step.
ImeActivationFailedException The requested input method editor could not be activated. Verify browser/platform support and whether the test environment has the required input method.
ImeNotAvailableException The requested input method is unavailable. Use an available input method or a test environment that supports the required one.
InvalidSwitchToTargetException The requested frame or window target is invalid. Refresh the list of frames/windows and switch to a live target in the correct order.
NoSuchCookieException The requested cookie is not present. Check current domain and cookie path, and verify the cookie was set and not cleared.
NoSuchAttributeException The requested attribute is not available on the element. Check the attribute name and current element; for live properties such as value, use the appropriate property/API.
InvalidCookieDomainException The cookie domain is inconsistent with the current browsing context. Switch to the correct site before adding the cookie and check the requested domain.
ElementNotVisibleException The element is not visible for the requested operation. Wait for visibility if expected, or correct the locator if it found a hidden duplicate.

5. Protocol, remote-end, and less common binding exceptions

Exception What it indicates Verify and fix
ErrorInResponseException The remote end returned an error response. Inspect the complete response and driver logs; identify the failing command before changing the test.
InvalidCookieDomainException The cookie domain does not match the active host. Use the active domain and valid cookie attributes.
InvalidElementCoordinatesException The target coordinates are not valid for the current element geometry. Re-read element geometry after layout changes and scroll into the active viewport.
InvalidSelectorException The locator syntax or strategy is invalid. Validate syntax and strategy against the current DOM.
InvalidSessionIdException The session has already ended. Correct session lifecycle and command ordering.
InvalidSwitchToTargetException The target context cannot be selected. Re-enumerate available windows/frames and switch using the right handle or frame element.
NoAlertPresentException No alert exists for the attempted alert command. Wait for an expected alert or remove the unnecessary command.
NoSuchElementException The current search returned no element. Check page, selector, and timing independently.
RemoteDriverServerException A remote driver server reported an error. Check remote endpoint health, server logs, and command payload; isolate with a minimal request.
SessionNotCreatedException Browser startup did not produce a WebDriver session. Check browser/driver versions, executable access, and environment restrictions.
UnexpectedTagNameException A helper received an element with an unexpected tag. Check the locator and use the helper only with the expected element type.
UnknownErrorException The remote end reported an unspecified error. Capture complete logs and reproduce with a minimal command; look for driver-specific diagnostics.
UnknownMethodException The remote end does not support the method. Check version compatibility and endpoint routing.
UnreachableBrowserException The browser became unreachable during a command. Check whether the browser crashed or was terminated, then inspect resource limits and driver logs.
UnsupportedCommandException The requested operation is unsupported. Use a supported command or compatible browser/driver combination.
WindowNotFoundException A requested window is unavailable. Inspect active window handles and the order in which the test opens and closes tabs.
NoSuchProcessException A process needed by the driver is missing. Check browser process startup, permissions, and environment cleanup.

Inventory note: The tables are a practical 49-row troubleshooting index, and some legacy or related names overlap in meaning. The Selenium Python API may alias names or retain compatibility classes; this is not a promise of 49 unique runtime failure modes. Check the versioned [Python exception reference](https://www.selenium.dev/selenium/docs/api/py/selenium_common/selenium.common.exceptions.html) and your binding’s API before relying on a class name. The rows above intentionally group remedies by failure family; repeated patterns point to the same underlying diagnosis.

Fix the most commonly searched failures

Why am I getting NoSuchElementException?

Selenium did not find a match at the instant it searched. The page may be wrong because an earlier action failed, the element may not have appeared yet, or the selector may have changed. Print the current URL, inspect the live DOM, and test the selector in the browser’s developer tools. If the element loads asynchronously, wait for the relevant condition rather than sleeping for an arbitrary duration.

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

button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-test='save']"))
)
button.click()

How do I fix StaleElementReferenceException?

A stored element handle no longer points to an accessible element. A page refresh, navigation, DOM replacement, or context change can cause it. Reacquire the element after the update. If the page switched into an iframe or another window, restore the intended context before locating it.

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

locator = (By.CSS_SELECTOR, "[data-test='status']")
status = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))
print(status.text)

Why is Selenium clicking the wrong thing?

A WebDriver click targets the element’s center. If another element covers that point, Selenium can report interception or the page can receive an unintended interaction. Inspect overlays, cookie banners, sticky navigation, dialogs, and animations. Wait for the obstruction to disappear or position the element so its center is clear. JavaScript-triggered clicks can hide a real usability problem, so use them only when the test is intentionally checking a script-level action.

Why can’t Selenium create a browser session?

Session startup belongs to browser and driver setup. Check that the browser is installed and executable, the driver supports that browser version, and the user running the test has permission to launch both. In containers or CI, also check sandbox restrictions and required system libraries. Driver discovery behavior depends on Selenium version and environment; follow the current [driver location guidance](https://www.selenium.dev/documentation/webdriver/troubleshooting/errors/driver_location/).

Practical fixes by failure family

Timing and synchronization

  • Wait for a state that reflects the next action: presence, visibility, clickability, a URL change, or a specific text value.
  • Use explicit waits for dynamic pages. Avoid mixing implicit and explicit waits in ways that make actual wait durations hard to predict.
  • Do not use a longer timeout to mask a wrong page, broken navigation, or incorrect selector.

Locators and page state

  • Prefer stable attributes intended for tests, such as a dedicated data attribute, when the application provides them.
  • Confirm that the current page is the expected one before investigating a missing element.
  • Use CSS with CSS syntax and XPath with XPath syntax; do not pass one strategy’s expression to another.

DOM lifecycle and context

  • Store locators across page updates, then find fresh elements after the update.
  • Track window handles when a new tab opens, and switch explicitly.
  • Switch into the correct iframe before locating its contents and return to the default content when finished.
  • For shadow DOM, reacquire the host and root after component replacement.

Visibility and hit testing

  • Check displayed and enabled state, scroll position, and whether an overlay covers the center of the target.
  • Wait for animations or modal transitions to finish before clicking.
  • Use keyboard input for controls where it matches the user interaction being tested.

Session and driver setup

  • Keep driver creation and teardown paired; avoid commands after quit().
  • Log Selenium, browser, and driver versions in CI failure output.
  • Reproduce with another browser if the error may come from a browser-specific driver.
  • Use Selenium Manager or the binding’s current Service configuration rather than copying setup instructions written for an old browser release.

ScreenshotNeo option for visual checks

To inspect a rendered page without creating a local browser-driver session, ScreenshotNeo accepts a URL and returns an image or PDF. This helps with visual debugging snapshots; it does not execute Selenium interactions. The ScreenshotNeo API docs cover request options and response headers.

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`ScreenshotNeo returned ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await (await import('node:fs/promises')).writeFile('shot.webp', bytes);

Or skip the browser setup

One GET request returns a screenshot. 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; paid plans start at $5 for 3,000. See the API docs for options and sign up for 1,000 free screenshots a month, no card.

Performance, reliability, and cost notes

  • Wait precisely: Waiting for a specific state reduces wasted time compared with repeated fixed sleeps while keeping failures informative.
  • Capture evidence selectively: Screenshots and page source help diagnose failures, but save them on failure rather than every passing step to control artifact volume.
  • Keep sessions scoped: Reuse a session within a test when appropriate, but isolate tests whose state, cookies, windows, or browser profile can interfere with one another.
  • Separate infrastructure from page failures: Record browser and driver versions and preserve startup logs so CI environment problems do not look like locator bugs.
  • Screenshot cost: Local Selenium has no per-shot API charge, but it uses browser and machine resources. ScreenshotNeo bills only clean shots; bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. Each response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its plans are Free (1,000/month), Starter $5 (3,000), Growth $15 (15,000), Pro $39 (60,000), Scale $99 (250,000), and Business $249 (1,000,000); yearly billing gives two months free, and all features are available on every plan.

Troubleshooting checklist

  • [ ] Does the current URL and title prove the test reached the expected page?
  • [ ] Does the locator match the current DOM, using the correct locator strategy?
  • [ ] Is the wait checking the state the next action actually needs?
  • [ ] Did navigation, a DOM update, or a context switch invalidate a stored element?
  • [ ] Is the element displayed, enabled, in view, and unobstructed at its center?
  • [ ] Is the WebDriver session still active?
  • [ ] Can the browser and driver start together under the CI/container user and permissions?
  • [ ] Could the failure be specific to the browser driver? Have you compared another browser?

FAQ

Does Selenium have exactly 49 exceptions?

No universal, cross-language list of exactly 49 is established by the cited sources. This guide uses a 49-row practical index based on Python’s 4.50.0 exception reference; aliases, legacy names, and language bindings make raw counts differ.

Should I retry every Selenium exception?

No. A retry can make transient rendering races less likely, but it cannot repair a wrong selector, closed session, missing frame, or incompatible driver. Identify the underlying state first.

When should I use a screenshot instead of page source?

Use a screenshot to see layout, overlays, and what a human would see. Use page source and DOM inspection to verify element structure, attributes, and whether the target exists.

Can ScreenshotNeo replace Selenium?

No. ScreenshotNeo captures a URL as an image or PDF. Selenium drives a browser for interactions and assertions. Use a screenshot API for visual capture and Selenium when the test needs browser actions.