How to Verify That an Image Displays Correctly with Selenium
Check whether an image loaded, appears at the expected size, and looks right with Selenium waits and screenshot comparisons.

To verify an image with Selenium, wait for the specific image to reach the state your test needs, then check its load state and intrinsic dimensions. For a practical loaded-image assertion, require complete === true, naturalWidth > 0, and naturalHeight > 0. Check visibility and rendered dimensions separately when layout matters. If “correctly” means the picture itself is right, capture a screenshot and compare it under controlled conditions.
complete alone does not prove success: a broken image can also be complete. Navigation finishing is not proof that client-side content or a lazy image is ready. Selenium recommends explicit waits for the condition your test depends on. [Selenium waiting strategies](https://www.selenium.dev/documentation/en/webdriver/waits/) · [MDN: complete](https://github.com/mdn/content/blob/main/files/en-us/web/api/htmlimageelement/complete/index.md?plain=1)
1. Decide what “displays correctly” means
Image tests often conflate three separate requirements. Pick the one that matches the feature under test; combine them when the product requirement calls for it.

| Check | What it tells you | What it does not prove |
|---|---|---|
| Resource loaded | The image element completed and has positive intrinsic dimensions. | That the image is visible, correctly placed, or the expected picture. |
| Layout is right | The element is displayed and its rendered dimensions meet the requirement. | That the fetched image content is the intended image. |
| Rendered appearance is right | A screenshot matches the visual expectation under your comparison policy. | That every pixel will remain identical across browsers or environments. |
The browser’s naturalWidth and naturalHeight describe intrinsic, density-corrected image dimensions. They are zero when the image data or dimensions are unavailable. CSS can scale or otherwise alter the rendered dimensions, so natural size and on-page size are distinct checks. [MDN: naturalWidth](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth) · [MDN: naturalHeight](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight)
2. Install Selenium and start a browser
The examples below use Python and Selenium WebDriver. They expect a running local browser driver supported by your Selenium setup. Install the Python package with:
python -m pip install selenium
Save the following as verify_image.py. Replace the example page URL and image selector with your own. The script waits for the image element, scrolls it into view to trigger common lazy-loading behavior, waits for a successful resource state, then checks visibility and optional rendered dimensions.
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
PAGE_URL = "https://example.com/product"
IMAGE_SELECTOR = "img#hero-image"
EXPECTED_RENDERED_WIDTH = 640
EXPECTED_RENDERED_HEIGHT = 360
options = webdriver.ChromeOptions()
# Uncomment to run without opening a visible browser window.
# options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
try:
driver.set_window_size(1440, 1000)
driver.get(PAGE_URL)
wait = WebDriverWait(driver, 20)
image = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, IMAGE_SELECTOR))
)
# Lazy-loaded images may not request their source until near the viewport.
driver.execute_script(
"arguments[0].scrollIntoView({block: 'center'});", image
)
# Wait for both completion and actual intrinsic image data.
wait.until(lambda d: d.execute_script("""
const img = arguments[0];
return img.complete && img.naturalWidth > 0 && img.naturalHeight > 0;
""", image))
state = driver.execute_script("""
const img = arguments[0];
const rect = img.getBoundingClientRect();
const style = getComputedStyle(img);
return {
complete: img.complete,
naturalWidth: img.naturalWidth,
naturalHeight: img.naturalHeight,
renderedWidth: rect.width,
renderedHeight: rect.height,
display: style.display,
visibility: style.visibility,
opacity: style.opacity
};
""", image)
assert state["complete"], f"Image did not complete: {state}"
assert state["naturalWidth"] > 0, f"No intrinsic width: {state}"
assert state["naturalHeight"] > 0, f"No intrinsic height: {state}"
assert image.is_displayed(), f"Image is not displayed: {state}"
assert state["renderedWidth"] == EXPECTED_RENDERED_WIDTH, state
assert state["renderedHeight"] == EXPECTED_RENDERED_HEIGHT, state
print("Image checks passed:", state)
finally:
driver.quit()
For a responsive layout, exact dimensions may be brittle. Replace equality with a range or a requirement such as a minimum width, and set the viewport to the intended test size. If the page uses a CSS selector other than an img element, adapt the checks: naturalWidth applies to HTMLImageElement, not background images.
3. Understand the wait and the image state
driver.get() returning does not guarantee that a framework has rendered the target or that a particular image has loaded. Selenium’s navigation wait is tied to document readiness, while JavaScript can continue changing the page afterward. Wait for the application condition and image condition your test needs instead of adding a fixed sleep. [Selenium: waiting strategies](https://www.selenium.dev/documentation/en/webdriver/waits/)

The core browser check can be inspected directly through Selenium’s script execution:
state = driver.execute_script("""
const img = document.querySelector("#hero-image");
return {
exists: Boolean(img),
complete: img?.complete ?? false,
naturalWidth: img?.naturalWidth ?? 0,
naturalHeight: img?.naturalHeight ?? 0,
renderedWidth: img?.getBoundingClientRect().width ?? 0,
renderedHeight: img?.getBoundingClientRect().height ?? 0
};
""")
print(state)
This snapshot is useful for diagnostics, but a one-time read can race with loading. Put the desired predicate inside a Selenium explicit wait, as in the full example. The success condition is completion and positive intrinsic dimensions. MDN explicitly notes that broken images can have complete === true. [MDN: complete](https://github.com/mdn/content/blob/main/files/en-us/web/api/htmlimageelement/complete/index.md?plain=1)
Wait for application state too
If the image element is inserted only after an API response, waiting for its presence is a useful first condition. If your application exposes a meaningful state, such as a product card becoming ready, wait for that too. An image may be present with an empty or placeholder source while the application is still preparing the final content. Avoid assuming that the presence of the element means the final image has been selected.
Lazy loading and responsive sources
Lazy-loaded images may not have begun fetching when the window’s load event fires. Scroll the target into its expected viewport before the loaded-image wait. Responsive srcset and sizes can cause the browser to select different source files at different viewport sizes; test at a deliberate viewport and verify the selected source if source choice is part of the requirement. [MDN: img element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img)
4. Verify visibility and rendered size
Positive natural dimensions say that image data is available; they do not say the image can be seen. Selenium’s is_displayed() checks whether the element is displayed, and getBoundingClientRect() supplies its current rendered box. The example also records CSS display, visibility, and opacity to help explain an absent-looking image.
Choose assertions that reflect the interface contract:
- Use
is_displayed()when the element must be shown. - Check rendered width and height against a range when responsive scaling is expected.
- Check the element’s location or container bounds if placement or clipping matters.
- Inspect overlays, overflow clipping, opacity, and stacking when a loaded image appears missing.
A zero rendered width or height can indicate CSS sizing, a collapsed container, or an element that is not participating in layout. A nonzero box still does not prove that the expected picture is being served. For that, assert the expected URL or compare the rendered result.
5. Verify the actual picture with a screenshot
A load assertion passes even if the server returned the wrong successful image. When the requirement concerns visual content, capture the element and compare it to a reference. Selenium supports screenshots of the browsing context and of individual elements. [Selenium: browser screenshots](https://www.selenium.dev/documentation/webdriver/browser/windows/)
image.screenshot("hero-image.png")
driver.save_screenshot("product-page.png")
Use an element screenshot for a focused image check and a page screenshot when surrounding layout is part of the requirement. The comparison method and tolerance are project decisions; there is no universal pixel threshold that is correct for every page. Before interpreting a difference, keep these inputs stable:
- Browser and browser version, viewport size, and device scale factor.
- Fonts, locale, timezone, and any responsive breakpoint inputs.
- Image source data, test account, and dynamic page content.
- Animations, carousels, timestamps, and asynchronous widgets that can change between captures.
If only the image identity matters, checking a stable expected src or selected source can be less sensitive than a full visual comparison. If crop, orientation, or visual treatment matters, screenshot comparison is more representative. Keep the assertion aligned with the user-visible requirement.
6. Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
complete is true, but the image is broken. |
Completion includes a broken-image state. | Also require positive naturalWidth and naturalHeight. |
| Image element is not found. | Client rendering has not inserted it, or the locator is wrong. | Wait for the application state and use a stable selector; check frames or shadow roots if the app uses them. |
| Image never gets positive dimensions. | Failed request, invalid URL, blocked resource, or lazy loading has not started. | Scroll into view, inspect the source and browser console/network logs, then allow a bounded wait for the app’s actual load. |
| Intrinsic dimensions pass but image looks absent. | CSS hides, clips, covers, or makes the element transparent. | Inspect rendered box, visibility, opacity, overflow, and overlays; capture a screenshot. |
| Image loads, but the wrong picture appears. | The URL or responsive source resolves successfully to unintended content. | Assert the intended source or compare the rendered image against a controlled reference. |
| Screenshot comparison fails intermittently. | Viewport, fonts, animation, data, or browser rendering varies. | Stabilize the capture environment and dynamic inputs; define a deliberate comparison policy. |
| Exact size assertion fails on another viewport. | Responsive CSS changes the rendered dimensions. | Set the intended viewport and assert a range or breakpoint-specific value. |
| Test times out even though page navigation succeeded. | Navigation readiness did not include later client-side work. | Use explicit waits for the element, app state, and image predicate rather than a fixed sleep. |
7. Reliability, speed, and maintenance
Explicit waits make the test respond as soon as the condition is true, while keeping a finite upper bound on failure. Fixed sleeps slow passing tests and can still be too short under load. Use a stable locator and wait for one meaningful condition at a time so a timeout points toward a specific missing state.
Keep image assertions narrow. A resource-load test is usually cheaper to diagnose than a page-wide screenshot diff. Add visual comparisons where appearance is a requirement, then control the browser environment and test data. If images are large or numerous, test the specific images the feature depends on rather than waiting for every image in the document without need.
Do not treat every failed load as a Selenium issue. The application may have returned a bad URL, the server may have failed, or the browser may be waiting for a lazy-loading trigger. Capture useful state in failure output: selector, current source, complete flag, natural dimensions, rendered box, and screenshot. This makes failures easier to distinguish without weakening the assertion.
8. Or skip the browser setup
If you need a screenshot for a visual check, ScreenshotNeo provides a website screenshot API: one GET request with a URL returns a PNG, JPEG, WebP, or PDF. See the [ScreenshotNeo documentation](https://screenshotneo.com/docs/) for the API and options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/product -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/product"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/product' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', new Uint8Array(await res.arrayBuffer()));
ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. See [ScreenshotNeo](https://screenshotneo.com) and [sign up free](https://screenshotneo.com/account/sign-up/).
FAQ
Does Selenium have a built-in “image loaded” expected condition?
Use an explicit wait with a browser-side predicate that checks the image element’s completion and intrinsic dimensions. This expresses the actual image condition instead of assuming page navigation is enough.
Should I check src or currentSrc?
Check the expected source when selecting the correct asset is part of the requirement. For responsive images, the browser may choose a source based on viewport and srcset; the selected source can differ from the src attribute.
Can these checks verify CSS background images?
Not directly with naturalWidth, which belongs to image elements. For a background image, inspect the computed background style and verify the rendered result with a screenshot if appearance is the requirement.
Is a screenshot diff always better than checking dimensions?
No. Use dimensions for layout requirements and screenshot comparison when the visible appearance or content matters. Visual comparisons need controlled inputs and an intentional policy for acceptable differences.


