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.

To capture one element without a page overlay, first decide whether the popup is a browser-native JavaScript dialog or an element rendered in the page. Use driver.switch_to.alert for an alert, confirm, or prompt. For a cookie banner, modal, newsletter form, or chat widget, locate its DOM element, dismiss it normally or hide it with driver.execute_script, then locate the target again and call target.screenshot('target.png').

Identify which kind of popup you have

Selenium cannot handle every popup through the same API. A JavaScript alert, confirm, or prompt is a browser-native dialog outside the page DOM. A cookie notice, modal, newsletter form, or chat bubble is ordinary page content, so you must locate it as an element.

Popup type How to detect and handle it Important decisions
JavaScript alert Wait for an alert and inspect or accept it through driver.switch_to.alert. Whether to accept or dismiss it; there is no input field.
JavaScript confirm Wait for the alert, then call accept() or dismiss(). Choose the page action you want before continuing.
JavaScript prompt Read the text, enter a value with send_keys(), then accept or dismiss. Supply text only when the prompt requires it.
DOM overlay, modal, consent banner, or widget Locate the element, click its own close or consent control, or change its style with JavaScript. Selector reliability, rerendering, frames, shadow roots, and whether changing page state is acceptable.

Use the page’s visible close or consent control when you need normal site behavior or a stored consent state. Hiding the node directly is useful when the objective is only a clean image and changing the active document’s styling is acceptable.

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

Set up an element screenshot in Selenium

The following script opens a page, waits for an overlay, hides it, waits for the target element, and saves only that WebElement as a PNG. Replace both CSS selectors with selectors from the page you automate. They are examples, not universal selectors.

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

url = 'https://example.com'
overlay_selector = '.popup-overlay'
target_selector = '#target'

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

try:
    driver.get(url)

    # Wait until the overlay exists in the current document.
    overlay = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, overlay_selector))
    )

    # Hide the overlay for this active document.
    driver.execute_script(
        "arguments[0].style.display = 'none';", overlay
    )

    # Locate the target after the DOM/style change and capture only it.
    target = wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, target_selector))
    )
    target.screenshot('target.png')
finally:
    driver.quit()

WebElement.screenshot() writes an image of the individual element, so a full-browser screenshot followed by a crop is not required for the basic case. The output is a PNG. Keep the browser and driver open until the file has been written.

Hide a DOM overlay safely

1. Find a selector that identifies the overlay

Inspect the page and choose a stable ID, class, data attribute, or other CSS selector. Prefer a selector tied to the component rather than a generated class that changes on every build. If several overlays can appear, handle each one explicitly instead of hiding every element with a broad selector such as div.

2. Wait for the page state

Use an explicit wait for the overlay and another for the target. A fixed sleep can finish before a delayed consent script runs or waste time when the page is already ready. presence_of_element_located confirms that Selenium can find the node; visibility_of_element_located confirms that the target can be seen.

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.

3. Change only the active document

driver.execute_script runs JavaScript in the currently selected window and frame. Passing the WebElement as an argument avoids rebuilding a selector inside the script:

overlay = wait.until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.consent-banner'))
)
driver.execute_script(
    "arguments[0].style.display = 'none';", overlay
)

Setting display to none removes the overlay from layout and hit-testing for that document. It does not accept cookies, submit a form, or tell the site’s own code that consent was given.

4. Reacquire elements after a change

Locate the target after hiding or dismissing the overlay. A rerender can detach the old WebElement reference and produce a stale element error. If the site rebuilds the target later, locate it again immediately before the screenshot.

Handle JavaScript alerts, confirms, and prompts

Do not search for a native dialog with a CSS selector. Wait for it through Selenium’s alert interface:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
alert = wait.until(EC.alert_is_present())
print(alert.text)
alert.accept()       # Use alert.dismiss() when cancel is the desired action.

For a prompt, enter text before accepting:

alert = wait.until(EC.alert_is_present())
print(alert.text)
alert.send_keys('value supplied by the test')
alert.accept()

After accepting or dismissing, wait for the target element again. The dialog may have blocked page execution, and the page can change as soon as it closes.

Frames, shadow roots, and pages that recreate the popup

Wrong frame

Selenium searches and executes scripts in the currently selected frame. If the overlay is inside an iframe, switch to that frame before locating or changing it:

frame = wait.until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'iframe.consent-frame'))
)
driver.switch_to.frame(frame)

inner_overlay = wait.until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.overlay'))
)
driver.execute_script(
    "arguments[0].style.display = 'none';", inner_overlay
)

driver.switch_to.default_content()

Switch back to the top document before locating a target that is outside the iframe. If the target is also inside the frame, capture it before switching back.

Shadow DOM

A selector in the light DOM may not reach an overlay inside a shadow root, particularly a closed shadow root. Inspect the component’s structure and use the site’s exposed close control or a shadow-aware strategy supported by your Selenium setup. There is no universal CSS selector that reaches every component implementation.

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

Overlay recreated after you hide it

Some consent managers or single-page applications recreate their node after a route change or asynchronous render. Wait for the new instance, hide it again, and reacquire the target. If the component repeatedly returns, clicking its own close or consent control may be more reliable than applying a style once.

Prefer a normal close action when page behavior matters

When your test is meant to represent a real visitor, click the visible close, reject, or accept button instead of simply hiding the container. That lets the site’s event handlers update consent state and remove any associated backdrop. A direct style change is appropriate for a visual capture where those side effects are not wanted.

close_button = wait.until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, '.popup-close'))
)
close_button.click()

target = wait.until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, '#target'))
)
target.screenshot('target.png')

Make the capture deterministic

  • Wait for the specific overlay or alert instead of relying on a global sleep.
  • Wait for the target’s visibility after the popup action.
  • Use a stable selector and verify that it identifies one intended element.
  • Reacquire references after a rerender or frame switch.
  • Keep the same browser, driver, viewport, and page state when comparing images.
  • Open the resulting PNG during development to confirm that the element was not clipped or covered by another layer.

An element screenshot reflects the actual browser and driver combination. Selenium’s API does not promise pixel-identical output across every environment, so validate the image in the environment used for your automation.

Troubleshoot common failures

Symptom Likely cause Fix
NoAlertPresentException The popup is a DOM element, or the alert has not appeared yet. Use an explicit alert_is_present() wait for native dialogs; otherwise locate the overlay in the page.
TimeoutException while locating the overlay The selector is wrong, the overlay is delayed, or it is in another frame. Check the live DOM, increase the explicit wait only when justified, and switch to the containing frame.
Overlay remains visible The script ran in the wrong document, the site recreated the node, or another backdrop is present. Confirm the selected window/frame, inspect for a second overlay, and apply the change after the final render or use the close control.
StaleElementReferenceException A rerender detached the WebElement. Discard the old reference and locate the overlay or target again.
Target screenshot is blank or incomplete The target was captured before it became visible, or lazy content had not loaded. Wait for visibility and the page state that makes the content available; inspect the saved PNG.
CSS selector finds nothing inside an iframe Selenium is still in the top document. Switch into the iframe, perform the lookup, then return to the default content when appropriate.
Popup returns on every navigation Hiding it changed only the current DOM and did not persist consent. Use the site’s consent action when persistence is required, or repeat the hide step after each navigation.

Performance, reliability, and cost considerations

The main reliability cost of this approach is page variability: delayed scripts, different selectors, frame boundaries, and rerenders. Explicit waits reduce race conditions without forcing every run to pause for a maximum sleep. Hiding an element is fast, but it can produce a visually clean image that does not represent a consented visitor. Clicking the site’s control takes more coordination but preserves normal behavior.

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

A local Selenium workflow also requires a browser, a compatible driver, and your own handling for navigation failures, retries, storage, and output files. When you need many URLs or a repeatable screenshot service, an API can move those concerns out of your script.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is the first API alternative to try when you want clean page captures: it removes cookie and consent banners, newsletter popups, and chat widgets before capture, bills only clean shots, and has a $5 paid plan for 3,000 shots.

One GET request returns a PNG, JPEG, WebP, or PDF. The API can capture a full page or one element by CSS selector, and supports custom CSS and JavaScript when a site needs a special adjustment. Its cleanup steps can be turned off individually.

cURL

See the ScreenshotNeo API documentation for the current parameter reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G 'https://api.screenshotneo.com/v1/shot' -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python with requests

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()));

Why the API avoids common popup failures

  • Consent banners, newsletter popups, and chat widgets are removed before the shot.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and whether the request was billed through X-Page-Verdict and X-Billed.
  • You can wait for a selector, a delay, or network idle; click an element before capture; hide selectors; block ads, trackers, requests, or resource types; and provide headers, cookies, a user agent, or Authorization.
  • For automation, it supports full-page lazy-image loading, dark mode, device presets or custom viewports, retina scale, transparent backgrounds, resizing, a chosen cache TTL, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification.
  • An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Plans

Plan Allowance and price
Free 1,000 shots per month, no card
Starter $5 for 3,000 shots
Growth $15 for 15,000 shots
Pro $39 for 60,000 shots
Scale $99 for 250,000 shots
Business $249 for 1,000,000 shots

Every feature is included on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card.

FAQ

Can I capture an element without taking a full-page screenshot?

Yes. Once the overlay is handled, call screenshot() on the target WebElement. The saved PNG contains that element rather than the whole browser viewport.

Should I accept a cookie banner or hide it?

Accept or reject it when the test must preserve normal consent behavior. Hide it only when the capture itself is the goal and changing page state is acceptable.

Why does Selenium say an alert is not present when I can see a popup?

The visible popup is probably page DOM content rather than a native JavaScript dialog. Inspect it as an element and handle its selector, frame, or component boundary.

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

Frequently Asked Questions

Does hiding an overlay persist after navigation?

No. The style change applies to the active document. Repeat it after navigation or use the site’s consent control when persistent state is required.

What image format does Selenium WebElement.screenshot() create?

The Selenium WebElement screenshot method saves a PNG file.

Can a selector work across every website’s popup?

No. Popup markup and timing are site-specific, and frames, shadow roots, and rerenders can require a different strategy.

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.

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