How to Check Whether an Element Exists With Python Selenium
Learn reliable Selenium checks for DOM presence, visibility, dynamic content, frames, shadow DOM, errors, waits, and screenshot verification.

To check whether an element exists right now, use Selenium’s plural lookup and test whether it returned any matches:
from selenium.webdriver.common.by import By
matches = driver.find_elements(By.CSS_SELECTOR, "#target")
if matches:
print("Element exists in the current DOM")
else:
print("No matching element was found")
find_elements() returns a collection. When nothing matches, Selenium returns an empty list, so the check does not need exception handling. This answers whether a matching node was found at the instant the lookup ran. It does not prove that the element is visible, enabled, inside the current frame, or still attached when you later use it.
This guide explains immediate checks, exception-based lookup, explicit waits, visibility, frames, shadow DOM, changing pages, common errors, and practical patterns for reliable Python Selenium tests.
1. Set up a runnable Selenium check
Install Selenium in the environment that runs your test:
python -m pip install selenium
Selenium 4 can obtain a compatible browser driver through Selenium Manager when you create a driver in the normal way. The following complete example opens a page, checks for an element, and always closes the browser:
from selenium import webdriver
from selenium.webdriver.common.by import By
URL = "https://example.com"
LOCATOR = (By.CSS_SELECTOR, "h1")
driver = webdriver.Chrome()
try:
driver.get(URL)
matches = driver.find_elements(*LOCATOR)
print(f"Found {len(matches)} matching element(s)")
finally:
driver.quit()
The locator is represented as a tuple so it can be reused with find_elements(), find_element(), and expected conditions.
2. Choose the right Selenium lookup
Selenium provides singular and plural finder methods. Use the method that matches the meaning of your test.

| Goal | Code | Result when there is no match |
|---|---|---|
| Branch on whether at least one element exists | driver.find_elements(By.ID, "target") |
Empty list |
| Get one expected element | driver.find_element(By.ID, "target") |
NoSuchElementException |
| Wait for DOM presence | WebDriverWait(...).until(EC.presence_of_element_located(locator)) |
TimeoutException after the wait |
| Wait until displayed | EC.visibility_of_element_located(locator) |
TimeoutException after the wait |
The official Selenium finder documentation describes find_element() as returning the first matching WebElement and find_elements() as returning matching elements as a collection. The Python API supports ID, name, XPath, CSS selector, class name, tag name, link text, and partial link text strategies.
Use find_elements() for a boolean existence test
exists = bool(driver.find_elements(By.ID, "target"))
if exists:
print("The element exists")
else:
print("The element does not exist")
This is concise and safe when “zero or more matches” is a normal outcome. If duplicate matches indicate a defect, check the count instead:
matches = driver.find_elements(By.CSS_SELECTOR, "[data-testid='save']")
if len(matches) == 1:
print("Exactly one save control exists")
elif not matches:
print("Save control is absent")
else:
raise AssertionError(f"Expected one save control, found {len(matches)}")
Use find_element() when the element is required
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
try:
element = driver.find_element(By.ID, "target")
except NoSuchElementException:
element = None
if element is None:
print("Required element is absent")
else:
element.click()
This form is useful when the next operation needs a WebElement. It makes absence exceptional, which is appropriate for a required control or an assertion.
3. Pick a locator that expresses the intended element
A stable locator reduces false negatives when a page layout changes. Prefer an ID or a dedicated test attribute when the application provides one:
by_id = driver.find_elements(By.ID, "account-menu")
by_test_id = driver.find_elements(By.CSS_SELECTOR, "[data-testid='account-menu']")
CSS selectors are useful for attributes, descendants, and states:
driver.find_elements(By.CSS_SELECTOR, "form#login input[name='email']")
driver.find_elements(By.CSS_SELECTOR, "button[data-state='open']")
XPath can express relationships that are awkward in CSS:
driver.find_elements(
By.XPATH,
"//button[normalize-space()='Continue']"
)
Text-based locators can be sensitive to localization and copy changes. Class names generated by a frontend build can also change without notice. Keep the locator as close as possible to a stable contract owned by the application.
4. Handle elements that appear after page load
An immediate lookup reports only the current DOM. JavaScript may add the target after navigation, an API response, a click, or a transition. In that case, use a bounded explicit wait.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
locator = (By.CSS_SELECTOR, "#target")
wait = WebDriverWait(driver, 10)
try:
element = wait.until(EC.presence_of_element_located(locator))
print("The element entered the DOM")
except TimeoutException:
print("The element did not appear within 10 seconds")
Add the missing import when using the exception:
from selenium.common.exceptions import TimeoutException
presence_of_element_located waits for a matching element to be present in the DOM. Selenium’s expected-condition documentation states that presence does not necessarily mean visibility. WebDriverWait.until() keeps polling until the condition returns a truthy value or the timeout expires. The documented default polling interval is 0.5 seconds, and NoSuchElementException is ignored by default during the wait. See the Python expected-conditions reference.
Wait for visibility when a user must see it
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(locator)
)
Selenium’s visibility condition requires the element to be displayed and have nonzero height and width. A visible element can still be covered by another element, disabled, outside the viewport, or unsuitable for a particular action, so verify the action separately.
Wait for a page-specific state
When the target appears only after an interaction, perform that interaction before waiting:
driver.find_element(By.ID, "open-dialog").click()
modal = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "[role='dialog']"))
)
Use a condition tied to the event you need. A long fixed sleep makes every run slower and still fails when the page takes longer than the chosen delay.
5. Distinguish existence, visibility, enabled state, and usability
These checks answer different questions:
- Exists: a lookup found at least one matching node.
- Present: the node is in the current DOM.
- Visible: Selenium considers it displayed with nonzero dimensions.
- Enabled: the control is not disabled according to WebDriver.
- Usable: the intended action can complete, including focus, overlay, viewport, validation, and application state.
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "submit"))
)
if not element.is_enabled():
raise AssertionError("Submit control is visible but disabled")
element.click()
Do not replace an existence check with is_displayed() unless visibility is the actual requirement. Conversely, do not treat a positive existence result as proof that a human can see or click the node.
6. Check elements inside frames and iframes
WebDriver searches the current browsing context. If the element is inside an iframe, locate the frame and switch into it first:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
frame_locator = (By.CSS_SELECTOR, "iframe.payment")
WebDriverWait(driver, 10).until(
EC.frame_to_be_available_and_switch_to_it(frame_locator)
)
exists = bool(driver.find_elements(By.NAME, "cardnumber"))
print(f"Card field exists inside frame: {exists}")
driver.switch_to.default_content()
After switching back to the default document, references and lookups apply to the outer page again. Nested frames require another switch for each level.
7. Check shadow DOM and changing elements
A normal document lookup may not reach nodes encapsulated in a shadow root. With Selenium 4, obtain the shadow root from its host and search within that context:
host = driver.find_element(By.CSS_SELECTOR, "my-widget")
shadow_root = host.shadow_root
matches = shadow_root.find_elements(By.CSS_SELECTOR, "button.save")
print(bool(matches))
The exact behavior depends on the component’s shadow-root mode and the Selenium/browser versions in your environment. If a frontend replaces a node after you found it, a stored WebElement can become stale. Locate the element again after the update instead of reusing an old reference.
8. Build reusable helper functions
A small helper keeps existence checks consistent across a test suite:
from selenium.webdriver.common.by import By
def element_exists(driver, by, value):
return bool(driver.find_elements(by, value))
def wait_for_presence(driver, locator, timeout=10):
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
return WebDriverWait(driver, timeout).until(
EC.presence_of_element_located(locator)
)
if element_exists(driver, By.ID, "target"):
print("Target is present now")
For test assertions, make failures descriptive:
def assert_exists(driver, locator):
if not driver.find_elements(*locator):
raise AssertionError(f"Expected element matching {locator!r}")
assert_exists(driver, (By.CSS_SELECTOR, "main article"))
9. Troubleshooting common failures
“NoSuchElementException” appears immediately
Cause: the element is not present at lookup time, the locator is wrong, or the page is in another frame.
Fix: verify the selector in browser developer tools, wait for the expected state, and switch into the correct iframe. Use find_elements() when absence is an expected branch.
The lookup returns an empty list even though the browser shows the element
Cause: the page is still rendering, the node is inside an iframe or shadow root, or the visible content belongs to a different tab or window.
Fix: wait for presence, switch browsing context, enter the shadow root, or switch to the correct window handle before searching.
presence_of_element_located succeeds but the click fails
Cause: presence says only that the node is in the DOM. It may be hidden, disabled, covered by an overlay, or outside the usable viewport.
Fix: wait for visibility or clickability, inspect is_enabled(), close overlays, scroll when needed, and use the locator again immediately before the action.
TimeoutException occurs
Cause: the condition never became true before the timeout. The target may genuinely be absent, the timeout may be too short for the environment, or an earlier navigation/action failed.
Fix: capture the current URL and page source for diagnosis, verify the preceding step, and choose a bounded timeout based on the operation’s expected behavior. Do not hide a broken locator by using an unbounded wait.
StaleElementReferenceException occurs
Cause: JavaScript replaced or removed the node after Selenium returned it.
Fix: wait for the page update to finish and locate the element again. Avoid keeping WebElement objects across operations that re-render the relevant component.
The test is slow or timing-sensitive
Cause: repeated fixed sleeps, broad page sleeps, or an uncontrolled mixture of waits.
Fix: wait on a specific condition with a finite timeout. Selenium supports implicit and explicit waits; keep your project’s wait policy consistent and consult the official waits guide for the installed Selenium version before combining mechanisms.
10. Performance and reliability practices
- Use the narrowest stable locator. It reduces matching work and makes failures easier to interpret.
- Use
find_elements()for one immediate branch instead of catching an exception for an expected absence. - Use explicit waits for asynchronous UI state, with the shortest timeout that covers the supported environment.
- Do not poll by repeatedly creating expensive page-wide XPath expressions when a specific ID or CSS selector is available.
- Re-locate after a known re-render instead of retrying operations on a stale reference.
- Keep assertions close to the action they protect so a failure identifies the missing state.
- Record the locator, URL, frame context, and timeout in failure output; this makes CI failures diagnosable.
11. Or skip the browser setup
If your goal is to capture a page or confirm what a public page renders, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture it can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off.
Here is the one-call request shown in the ScreenshotNeo documentation:
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(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo reports whether a response was a clean shot, cache hit, bot check, blank page, timeout, or failed load through the X-Page-Verdict and X-Billed headers. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing; only clean shots are billed. You can also use full-page capture with lazy images loaded, CSS selector element capture, custom CSS and JavaScript, waits, request blocking, headers and cookies, device presets, dark mode, PDFs, caching, signed links, asynchronous jobs, webhooks, bulk capture, and the usage API. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
Free accounts include 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.
12. FAQ
What is the simplest existence check?
bool(driver.find_elements(By.ID, "target")). It returns True when at least one matching element exists at that moment.
Should I use find_element() or find_elements()?
Use the plural method when no match is a normal branch. Use the singular method when one element is required and absence should raise or be handled as an exception.
Does existence mean the element is visible?
No. Use visibility_of_element_located when the requirement is that Selenium considers the element displayed with nonzero dimensions.
Why does a check pass once and fail later?
The DOM may be changing, the page may have navigated, or the element may be inside a different frame or window. Wait for the state you need and locate again after re-rendering.
Can Selenium check an element without clicking it?
Yes. Finder methods and expected conditions inspect the DOM without performing a click. Choose a visibility or enabled-state condition only when those properties matter.


