ScreenshotNeo

BlogHow-to

How to Check Page Content Before Capturing a Screenshot

Use Playwright locators and web-first assertions to verify content is ready before capturing reliable screenshots.

By the ScreenshotNeo team30 September 20268 min read

How to Check Page Content Before Capturing a Screenshot

A screenshot is only useful when it shows the state you intended to capture. The reliable pattern is to identify a locator that proves readiness, assert that locator with Playwright’s retrying web-first assertions, and capture only after the assertion passes. A fixed sleep can finish too early on a slow page or waste time on a fast one.

1. Direct answer: assert the content that proves readiness

Use this sequence:

  1. Navigate to the URL.
  2. Choose a stable, user-meaningful locator, such as a heading, result row, status message or main article container.
  3. Assert the expected state with await expect(locator).toBeVisible(), toHaveText() or another web-first assertion.
  4. Wait for a specific DOM state with locator.waitFor() when visibility or text is not the right signal.
  5. Capture the viewport, full page or a particular element after the readiness check succeeds.

Playwright describes locators as the central mechanism for auto-waiting and retry-ability. Assertions retry while the page settles, so they represent the condition you care about instead of an arbitrary elapsed time. See the Locator API and assertion documentation.

2. A complete Playwright workflow

Install Playwright and its browsers, then create a test that waits for meaningful content:

A semantic readiness assertion connects rendered content to the screenshot step.
A semantic readiness assertion connects rendered content to the screenshot step.
npm init playwright@latest
npx playwright install
import { test, expect } from '@playwright/test';

test('capture rendered results', async ({ page }) => {
  await page.goto('https://example.test/results', {
    waitUntil: 'domcontentloaded',
    timeout: 30_000,
  });

  const main = page.getByRole('main');
  const resultsHeading = main.getByRole('heading', { name: 'Results' });

  await expect(resultsHeading).toBeVisible({ timeout: 15_000 });
  await expect(main.getByRole('listitem')).toHaveCount(10, {
    timeout: 15_000,
  });

  await page.screenshot({
    path: 'results.png',
    fullPage: true,
  });
});

page.goto() waits for the selected navigation milestone, but navigation completion alone does not mean that application data has rendered. The heading and list count are the actual readiness signals in this example. Adjust the timeout to the slowest acceptable response for your environment rather than adding a sleep.

For a component screenshot, keep the same readiness gate and change the capture scope:

const chart = page.locator('[data-testid="revenue-chart"]');
await expect(chart).toBeVisible();
await chart.screenshot({ path: 'revenue-chart.png' });

Use semantic roles, labels, test IDs or stable attributes where possible. A long CSS path tied to layout is more likely to break when the page is redesigned.

3. Pick a readiness signal that matches the page

Page behavior Good readiness check Why
Server-rendered article getByRole('heading', { name: ... }) Confirms the meaningful content is present and visible.
Search or report results toHaveCount() plus a result heading Prevents a capture of an empty or partially populated list.
Loading indicator replaced spinner.waitFor({ state: 'hidden' }) Checks the state transition directly.
Lazy component locator.waitFor({ state: 'visible' }) Waits for the element to enter the visible state.
Element created asynchronously waitFor({ state: 'attached' }) Checks DOM presence even when the element is not visible.
Removed overlay waitFor({ state: 'detached' }) Ensures the blocking node no longer exists.

Prefer content assertions when the content itself matters:

await expect(page.getByRole('status')).toHaveText('Payment complete');
await expect(page.locator('[data-testid="article"]')).toContainText('Introduction');

Use toHaveText() for exact or normalized text and toContainText() when the element includes additional copy. If text changes by locale, assert a stable label, role or data attribute instead.

4. Waiting for DOM states without guessing

locator.waitFor() supports attached, detached, visible and hidden. The state should express what must be true before the image is taken:

const loading = page.locator('[aria-label="Loading"]');
await loading.waitFor({ state: 'hidden', timeout: 20_000 });

const dashboard = page.locator('[data-testid="dashboard"]');
await dashboard.waitFor({ state: 'attached' });
await expect(dashboard).toBeVisible();

Do not use page.isVisible() as the only readiness gate. That method returns immediately and does not provide the retry behavior of an assertion. Likewise, locator.all() does not wait for a changing list; calling it while results are loading can produce an incomplete or unpredictable array. Wait for a count, a completion status or another stable condition first.

5. Capture the correct scope

Choose the capture scope deliberately:

  • Viewport: await page.screenshot({ path: 'viewport.png' }) captures what the current viewport shows.
  • Full page: await page.screenshot({ path: 'full.png', fullPage: true }) captures the full scrollable document.
  • Element: await locator.screenshot({ path: 'component.png' }) captures the element’s visible region.

An element screenshot does not automatically include all content hidden inside that element’s own scroll area. If the component is a scrollable panel, either change its CSS before capture, scroll it deliberately, or capture the page after expanding the panel.

await page.locator('#results-panel').evaluate((node) => {
  (node as HTMLElement).style.maxHeight = 'none';
  (node as HTMLElement).style.overflow = 'visible';
});
await page.locator('#results-panel').screenshot({ path: 'all-results.png' });

6. Dynamic content, animations and lazy loading

Modern pages can satisfy a basic visibility check while still changing visually. Add assertions for the data that must be complete, and handle animations when repeatability matters.

await expect(page.getByRole('heading', { name: 'Orders' })).toBeVisible();
await expect(page.getByTestId('orders-table').getByRole('row')).toHaveCount(25);

await page.addStyleTag({
  content: `*, *::before, *::after {
    animation: none !important;
    transition: none !important;
    caret-color: transparent !important;
  }`,
});

await page.screenshot({ path: 'orders.png', fullPage: true });

For lazy images, scroll through the page before a full-page shot so intersection observers run, or assert that important images have loaded:

await page.evaluate(async () => {
  await new Promise<void>((resolve) => {
    const distance = 600;
    const timer = setInterval(() => {
      window.scrollBy(0, distance);
      if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {
        clearInterval(timer);
        resolve();
      }
    }, 100);
  });
});
await page.waitForTimeout(300);
await page.screenshot({ path: 'lazy-loaded.png', fullPage: true });

A short settling delay can be reasonable after an explicit action such as scrolling, but it should supplement a state check, not replace one. For visual regression, Playwright’s screenshot assertions wait for two consecutive screenshots to match before comparison and can disable animations. See the PageAssertions API.

7. Common failures and fixes

Symptom Likely cause Fix
Screenshot contains a spinner Navigation finished before app data loaded. Assert the result heading, row count or completion status.
Assertion times out Wrong locator, blocked request, authentication issue or genuinely slow page. Inspect the locator in headed mode, listen for failed responses and verify credentials and URL.
Only some list items appear all() ran while the list was still changing. Wait for an expected count or stable completion marker before reading items.
Element is attached but absent in image It is outside the viewport, hidden by CSS or covered by an overlay. Use toBeVisible(), dismiss the overlay and scroll the element into view.
Full-page image misses content Lazy loading depends on scrolling or a nested scroll container is clipped. Trigger lazy loading and expand or separately capture nested scroll regions.
Two runs look different Animation, blinking cursors, rotating ads or time-dependent data. Disable animations, block unstable resources and use deterministic test data.
Text assertion fails in another locale Copy varies by language or account. Assert a stable role, test ID or locale-specific expected value.

When diagnosing a timeout, save a trace or inspect the page in headed mode. Check the URL after redirects, console errors, failed network responses and whether a cookie or login wall is covering the target. A readiness assertion cannot succeed when the required content never arrives.

8. Performance, reliability and cost considerations

  • Use the narrowest signal: Waiting for one stable container is usually faster and clearer than waiting for every network request.
  • Set bounded timeouts: A per-assertion timeout prevents one broken dependency from hanging a worker indefinitely.
  • Reuse a browser: In a test suite, create one browser process and isolated contexts per test rather than launching a new browser for every image.
  • Control external variability: Block analytics, ads and video when they are irrelevant, or serve fixtures for data that must be deterministic.
  • Retry carefully: A retry can recover from a transient navigation failure, but it should not hide a consistently broken readiness condition. Keep artifacts from failed attempts.
  • Capture after the last mutation: Avoid extra DOM changes between the assertion and screenshot unless they are part of the intended setup.

There is no universal wait duration. The correct timeout depends on the page, network and environment. Measure your own workflow and choose a limit that leaves room for normal variance while failing promptly when the page is unavailable.

9. Or skip the browser setup

If you need a clean image from a URL rather than a test assertion, ScreenshotNeo provides a single screenshot request. The API can wait for a selector, a delay or network idle, and supports full-page capture, element selectors, custom JavaScript and CSS, cookies, headers, user agents, timezone and geolocation settings. Read the ScreenshotNeo documentation for the complete option list.

Consent banners and overlays can be removed before an automated capture.
Consent banners and overlays can be removed before an automated capture.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
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 bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

Cookie banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts and cache hits are not billed, and response headers report the page verdict and whether the shot was billed. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. One thousand screenshots each month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

10. FAQ

Should I wait for network idle before every screenshot?

No. Network idle can be delayed by analytics, polling and open connections. Use it when it is a meaningful condition for your page; otherwise assert the content that proves readiness.

Is a fixed timeout ever acceptable?

A short delay can allow a known animation or scroll-triggered lazy load to settle, but pair it with a locator or state assertion whenever possible.

How do I wait for text that appears inside a canvas?

Canvas pixels are not ordinary DOM text. Assert the DOM state or data source that drives the canvas, then capture after the drawing code has completed.

What should I capture for a visual regression test?

Use a stable viewport or component locator, deterministic data, disabled animations and Playwright’s screenshot assertions so the comparison waits for consecutive images to stabilize.

Can an element screenshot include its entire scrollable content?

Not automatically. Locator screenshots capture the visible region. Expand the element, scroll it in controlled steps or capture each required region separately.