Website screenshots without cookie banners: a tested Playwright approach

By Siftwright team11 min read

You automate screenshots of a few hundred websites, open the results, and a third of them are the same picture: a grey overlay and a box asking you to accept cookies. The page you wanted is somewhere behind it.

There are three common fixes floating around: hide the banner with CSS, click the "accept" button, or block the consent script. Each works on some sites and quietly fails on others. We wanted to know where, so on 27 November 2026 we ran them against real sites with Playwright and Chromium and looked at every screenshot. This post covers what broke, why, and the script that ended up handling every banner in our sample.

Why the banner is harder than it looks

A cookie banner is usually not part of the page. It comes from a consent management platform (CMP) such as OneTrust, Sourcepoint, Usercentrics or Didomi, and each one injects its UI differently:

  • Plain DOM: a fixed div at the bottom or in the middle of the screen. OneTrust works this way, and so does most home-grown code.
  • Iframes: Sourcepoint renders its message in an iframe, often served from a subdomain of the site itself (sourcepoint.theguardian.com, sp-spiegel-de.spiegel.de). Selectors run on the main page cannot see the buttons inside.
  • Shadow DOM: Usercentrics attaches its UI to a shadow root under #usercentrics-root, so document.querySelector does not find the buttons either.
  • Scroll locks: modal banners set overflow: hidden on <body> or <html> so the page cannot scroll until you choose. Hide the banner and the lock stays.
  • Pay or OK walls: many European publishers offer "accept tracking" or "subscribe". The "reject" button is really a link to a checkout page.

There is also geography. Banners depend on where the visitor appears to be. Our runs came from a US data-centre IP, and several large sites showed no cookie banner at all from there. A scraper running from Frankfurt will see more banners than one in Ohio.

The test

We picked 20 well-known sites across news and retail in the UK, Germany, France, Italy, Spain, the Netherlands and the US. From our IP, six of them (including Reddit, eBay UK, Forbes and Adidas) returned a bot block page instead of content, which is a separate problem that no banner trick will solve. Six more showed no consent banner from the US. That left eight sites with a banner to remove: The Guardian, Der Spiegel, Le Monde, IKEA UK, Stack Overflow, Corriere della Sera, Le Figaro and El País.

For each site we took a 1280x800 screenshot with no cleanup, then with each method, and checked the images by eye. We also recorded document.documentElement.scrollHeight, because a full-page screenshot is only as tall as the document says it is.

Method 1: hide known CMP containers with CSS

The most common advice is to inject a stylesheet that hides the containers of well-known CMPs:

#onetrust-consent-sdk, [id^="sp_message_container"], #usercentrics-root,
#didomi-host, #CybotCookiebotDialog, .qc-cmp2-container, .fc-consent-root
{ display: none !important; }

This removed the banner on four of the eight sites: The Guardian, Der Spiegel, IKEA and Stack Overflow. It did nothing on Le Monde, Corriere della Sera or Le Figaro, which all run their own consent walls with their own class names. (El País served us a bot check on that run, so we could not judge it.)

It also has a second, less visible failure. On The Guardian and Der Spiegel the banner disappeared, but the page still could not scroll: <body> kept overflow: hidden, and the full-page screenshot came out exactly 800 pixels tall. On Corriere, <html> was locked in the same way. The first fix we tried made it worse. We added html, body { overflow: auto !important } to the stylesheet, which turned <body> into its own scroll box, and Stack Overflow's full-page height dropped from 2,810 pixels to 800. On The Guardian our rule did not even win: Sourcepoint adds a sp-message-open class to <html>, and its own !important lock is more specific than ours. What worked was to set overflow: visible as an inline !important style, which beats any stylesheet rule, and only on elements that were actually locked.

CSS hiding is cheap and does not change the site's state, but on its own it covered half of our sample.

Method 2: click the button

Clicking the button is closer to what a person does, and it removes the scroll lock along with the banner because the site's own code runs. The difficulties are finding the button and choosing which one to press.

Finding it. Playwright's role locators (getByRole('button', { name })) search inside open shadow roots automatically, and page.frames() includes cross-origin iframes, so looping over frames finds buttons inside Sourcepoint's iframe without extra work. Matching on the button's accessible name is more robust than matching CMP-specific selectors, but you need the words in each language: "Accept all", "Alle akzeptieren", "Tout accepter", "Accetta e continua".

Choosing it. We try a reject-style button first ("Reject all", "Necessary cookies only", "Continue without accepting") and fall back to accept. Rejecting keeps the capture closer to a privacy-respecting first visit and avoids loading ad and tracking scripts that slow the page down.

Clicking worked on all eight sites, but two cases needed handling:

  • Stack Overflow's OneTrust banner labels its reject button "Necessary cookies only". Our first pattern only knew "necessary only", so nothing was clicked until we added the exact phrase. Expect to grow these patterns as you meet new sites.
  • Le Figaro offers "Continue without accepting", which is a pay-or-OK choice. Clicking it navigated to the subscription page, and the "screenshot of the homepage" became a screenshot of a pricing table. The script now compares the URL before and after the click. If a reject click navigates away, it goes back and accepts instead.

On Le Monde the script clicked "Accept". The wall also has a "Reject all cookies" control, but it is not exposed as a button, so our reject pattern did not match it. Der Spiegel and Corriere della Sera offer no free reject at all, only "accept" or "subscribe".

The third approach is to abort requests to CMP hosts such as cdn.cookielaw.org with page.route(). Our sample shows why we did not pursue it. The two Sourcepoint sites load their consent UI from their own subdomains, and the custom walls on Le Monde, Corriere and Le Figaro come from first-party code. A blocklist of CMP domains would miss five of our eight sites. Some sites also refuse to render content until the consent framework answers, so blocking can leave you with a blank page instead of a banner.

Filter-list projects that target cookie notices (the ones browser extensions use) are a bigger version of the same idea. They can be worth a look at scale, but we did not test them for this post.

The combined script

What handled every banner in our sample was a combination: click (reject first, accept as a fallback, with the pay-or-OK guard), then hide known CMP containers as a safety net, then undo any scroll lock that is left. Here is clean.mjs:

// clean.mjs - remove cookie banners (and other big overlays) before a screenshot. Playwright.

// Containers of the common consent platforms (CMPs)
export const CMP_SELECTORS = [
  '#onetrust-consent-sdk',                                       // OneTrust
  '[id^="sp_message_container"]',                                // Sourcepoint
  '#usercentrics-root', '#usercentrics-cmp-ui',                  // Usercentrics
  '#didomi-host',                                                // Didomi
  '#CybotCookiebotDialog', '#CybotCookiebotDialogBodyUnderlay',  // Cookiebot
  '.qc-cmp2-container',                                          // Quantcast / InMobi Choice
  '.fc-consent-root',                                            // Google Funding Choices
  '#truste-consent-track', '.truste_box_overlay',                // TrustArc
  '.cky-consent-container', '.cky-overlay',                      // CookieYes
  '#iubenda-cs-banner', '.osano-cm-window', '#cmpbox', '#cmpbox2', // iubenda, Osano, consentmanager
];

// Try "reject" first, then "accept". Extend these for the languages you capture.
const REJECT = /^\s*(reject all|reject|decline|only essential|necessary cookies only|use necessary cookies only|continue without accepting|alle ablehnen|ablehnen|nur notwendige|tout refuser|refuser|continuer sans accepter|rifiuta|rechazar)\b/i;
const ACCEPT = /^\s*(accept all|accept|consent|agree|i agree|allow all|continue|ok|got it|alle akzeptieren|akzeptieren|zustimmen|tout accepter|accepter|accetta|aceptar)\b/i;

// Click the first visible matching button in any frame. Role locators also
// look inside open shadow roots, and page.frames() includes cross-origin iframes.
async function clickFirst(page, pattern) {
  for (const frame of page.frames()) {
    const btn = frame.getByRole('button', { name: pattern }).first();
    try {
      if (await btn.isVisible()) {
        const label = (await btn.innerText()).trim().slice(0, 40);
        await btn.click({ timeout: 1500 });
        return label;
      }
    } catch { /* frame went away or button is covered: try the next frame */ }
  }
  return null;
}

export async function removeCookieBanners(page) {
  const log = [];
  const url = page.url();

  let label = await clickFirst(page, REJECT);
  if (label) {
    await page.waitForTimeout(1500);
    // "Pay or OK" sites send you to a subscription page when you refuse. Go back and accept.
    if (page.url() !== url) {
      log.push(`"${label}" navigated away`);
      await page.goto(url, { waitUntil: 'domcontentloaded' });
      await page.waitForTimeout(3000);
      label = null;
    }
  }
  if (!label) {
    label = await clickFirst(page, ACCEPT);
    if (label) await page.waitForTimeout(1500);
  }
  if (label) log.push(`clicked "${label}"`);

  // Safety net: hide known CMP containers even if nothing was clicked.
  await page.addStyleTag({ content: CMP_SELECTORS.join(',') + '{display:none!important}' });

  // Undo the scroll lock a consent modal leaves on <html>/<body>. Inline !important beats
  // any stylesheet rule; 'visible' (not 'auto') keeps the viewport as the scroller.
  const unlocked = await page.evaluate(() => {
    let n = 0;
    for (const el of [document.documentElement, document.body]) {
      const cs = getComputedStyle(el);
      if (cs.overflow.includes('hidden')) { el.style.setProperty('overflow', 'visible', 'important'); n++; }
      if (cs.position === 'fixed') { el.style.setProperty('position', 'static', 'important'); n++; }
    }
    return n;
  });
  if (unlocked) log.push('unlocked scroll');
  return log;
}

// Hide any remaining fixed element covering a big share of the viewport
// (ad interstitials, newsletter modals, "support us" sheets). Headers and thin bars survive.
export async function hideLargeOverlays(page, minShare = 0.3) {
  return page.evaluate((minShare) => {
    const vw = innerWidth, vh = innerHeight, hidden = [];
    for (const el of document.querySelectorAll('body *')) {
      const cs = getComputedStyle(el);
      if (cs.position !== 'fixed' || cs.display === 'none' || cs.visibility === 'hidden') continue;
      // skip empty wrappers (closed modals): nothing to see, nothing to hide
      if (!el.innerText.trim() && !el.querySelector('img, iframe, video, canvas, svg')) continue;
      const r = el.getBoundingClientRect();
      const w = Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0));
      const h = Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
      if ((w * h) / (vw * vh) >= minShare) {
        el.style.setProperty('display', 'none', 'important');
        hidden.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
      }
    }
    return hidden;
  }, minShare);
}

And capture.mjs, which uses it to take a full-page screenshot:

// capture.mjs - full-page screenshot without cookie banners
// usage: node capture.mjs <url> [out.png]
import { chromium } from 'playwright';
import fs from 'node:fs';
import { removeCookieBanners, hideLargeOverlays } from './clean.mjs';

const url = process.argv[2];
const out = process.argv[3] || 'shot.png';
const stateFile = `consent-${new URL(url).hostname}.json`;

const browser = await chromium.launch();
const context = await browser.newContext({
  viewport: { width: 1280, height: 800 },
  // Reuse consent cookies/localStorage from an earlier run of the same site
  storageState: fs.existsSync(stateFile) ? stateFile : undefined,
});
const page = await context.newPage();
try {
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
  await page.waitForTimeout(3000); // consent scripts load late

  const log = await removeCookieBanners(page);
  const overlays = await hideLargeOverlays(page);
  if (overlays.length) log.push(`hid ${overlays.join(', ')}`);
  await context.storageState({ path: stateFile });

  await page.screenshot({ path: out, fullPage: true });
  const height = await page.evaluate(() => document.documentElement.scrollHeight);
  console.log(`${url}: ${log.join('; ') || 'nothing to remove'} -> ${out} (${height}px)`);
} finally {
  await browser.close();
}

Run it with node capture.mjs https://www.ikea.com/gb/en/ ikea.png. You need npm install playwright and a browser (npx playwright install chromium).

The fixed 3-second wait after loading is deliberate. Consent scripts often appear a second or two after domcontentloaded, and a screenshot taken earlier will miss the banner, then the banner will appear in the next frame. A waitForSelector on a known CMP container is faster when you only capture a few sites you know.

What happened on the eight sites

Site Consent UI CSS selectors only Final script
The Guardian Sourcepoint, iframe on own subdomain Hidden, but page locked at 800 px until unlocked Clicked "Continue"
Der Spiegel Sourcepoint, pay-or-OK Hidden, scroll lock needed removing Clicked "Consent and continue" (no free reject)
Le Monde Custom wall Not hidden Clicked "Accept"
IKEA UK OneTrust Hidden Clicked "Reject all"
Stack Overflow OneTrust Hidden Clicked "Necessary cookies only"
Corriere della Sera Custom wall, pay-or-OK Not hidden Clicked "Accetta e continua", unlocked <html>
Le Figaro Custom wall, pay-or-OK Not hidden Reject went to a subscription page; went back and accepted
El País Custom wall Bot check on that run Clicked "Accept and continue"

All eight final full-page screenshots showed the page content with no consent UI. Full-page heights ranged from 2,810 pixels (Stack Overflow) to about 49,000 (Corriere).

The banner is not the last overlay

Once consent was saved, a second visit with the same storage state skipped the banner entirely. Two sites then showed something else. The Guardian displayed a large "support us" fundraising sheet, and on one run Corriere della Sera showed a full-screen ad interstitial. The Independent, which showed no cookie banner from our IP, covered its homepage with a membership offer.

That is what hideLargeOverlays() is for. It hides any position: fixed element that covers at least 30% of the viewport and actually contains something. It removed The Guardian's fundraiser and The Independent's popup, and left headers and Der Spiegel's slim subscription strip alone. The "contains something" check came from a real false positive. IKEA keeps 14 empty, closed modal wrappers fixed over the whole viewport, and the first version of the function dutifully "hid" all of them. They were invisible, so the screenshot did not change, but the log was noise and a less careful rule could hide something that matters.

capture.mjs writes the browser's cookies and local storage to consent-<host>.json after each capture and loads them on the next run. On our second pass none of the eight sites needed a click. This is the cheapest improvement for monitoring jobs that capture the same sites every day, such as visual regression tests or link-preview thumbnails. Consent records expire, and sites re-ask when their vendor list changes, so keep the click logic as a fallback rather than relying on the file.

Limits worth knowing

  • Geography changes the results. Test from the region you will run in. A script tuned from a US IP will meet banners it has never seen when it runs in the EU.
  • Closed shadow roots cannot be searched by role locators. None of our eight sites used one, but some CMP builds do. The CSS safety net still hides those containers by host element.
  • Bot protection is a separate fight. Six of our 20 sites blocked a headless browser from a data-centre IP before any banner appeared, and El País did so on some runs. Hiding banners does not help there.
  • Lazy content still applies. If the page loads images on scroll, combine this with the scrolling approach from our post on blank lazy-loaded images in full-page screenshots.

Or let the API do it

If you would rather not maintain button patterns and browser fleets, the Siftwright Screenshot API has a blockCookieBanners option that is on by default. Like every approach in this post it is best-effort, and we did not re-run this sample through it for this article, so test it on the sites you care about. The parameters are in the API docs, and failed captures are not billed.

Related guides

Get the next guide by email

Practical tutorials on transcripts, screenshots, news data and agent tooling. A couple of emails a month at most.