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

With Playwright or Puppeteer, remove unwanted DOM nodes in the page context immediately before calling page.screenshot(). If you only need them hidden in the image, Playwright can instead inject CSS for the screenshot, leaving the page’s DOM intact. Use narrow selectors, wait for the page-specific state that creates the element, and run cleanup close to capture so dynamic scripts do not put it back.

Choose between removing an element and hiding it in the screenshot

There are two different goals that can look identical in a saved image:

  • Remove a node: change the document tree by calling element.remove(). Use this when subsequent page work should reflect the element’s absence.
  • Hide it for capture: change only screenshot rendering with CSS. Use this when the page should remain otherwise untouched and the unwanted element only needs to be absent from the image.

A third option is to capture just the component you need rather than the whole page. Playwright supports locator screenshots; Puppeteer supports ElementHandle.screenshot(). This can avoid dealing with overlays elsewhere on the page.

Remove selected elements with Playwright

After navigation and the page-specific readiness condition, evaluate a selector list in the page context. The following CommonJS example removes three example elements and saves a full-page PNG:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();

  try {
    await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
    // Replace this with a readiness condition specific to the target page.
    await page.locator('body').waitFor();

    const selectors = ['.cookie-banner', '#newsletter-modal', '.sticky-ad'];
    const removed = await page.evaluate((selectors) => {
      let count = 0;
      for (const selector of selectors) {
        document.querySelectorAll(selector).forEach((element) => {
          element.remove();
          count += 1;
        });
      }
      return count;
    }, selectors);

    console.log(`Removed ${removed} element(s)`);
    await page.screenshot({ path: 'page.png', fullPage: true });
  } finally {
    await browser.close();
  }
})();

Install Playwright and its browser using the instructions for your project and installed Playwright version. Replace https://example.com and all three example selectors with the actual page and elements you intend to remove. page.evaluate() runs the function in the page context, where document.querySelectorAll() can access that document’s DOM.

Remove matches for one locator

If one selector is enough, Playwright’s locator().evaluateAll() passes the current matching elements to a function:

await page.locator('.cookie-banner').evaluateAll((elements) => {
  elements.forEach((element) => element.remove());
});

await page.screenshot({ path: 'page.png' });

This acts on matches present when the evaluation runs. It does not keep watching for later insertions. Playwright describes locators as the central part of its auto-waiting and retry-ability, but creating or evaluating a locator is not a universal signal that a dynamic page has finished rendering. Use a readiness condition tied to the page’s actual behavior.

Hide elements only while Playwright captures the screenshot

When the DOM should remain unchanged, pass a stylesheet in the screenshot’s style option. Playwright applies it for the capture, so there is no separate removal step:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
await page.screenshot({
  path: 'page.png',
  fullPage: true,
  style: `
    .cookie-banner,
    #newsletter-modal,
    .sticky-ad {
      display: none !important;
    }
  `,
});

Replace the selectors with specific matches from the page. The documented screenshot stylesheet can reach Shadow DOM and inner frames, which is useful for content ordinary top-document selectors cannot reach. This is a rendering change for the screenshot, not deletion from the page’s document tree.

Masking is not removal

Playwright also offers screenshot controls such as masking locators. A mask covers matched content in the screenshot; it does not delete the nodes. Use masking when obscuring the content is sufficient, and choose CSS hiding or DOM removal when the visual result or page state calls for those instead.

Remove selected elements with Puppeteer

Puppeteer’s page-context evaluation supports the same workflow. This CommonJS example removes the selectors from the current document and then captures the page:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  try {
    await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
    // Replace this with a readiness condition specific to the target page.
    await page.waitForSelector('body');

    const selectors = ['.cookie-banner', '#newsletter-modal', '.sticky-ad'];
    const removed = await page.evaluate((selectors) => {
      let count = 0;
      for (const selector of selectors) {
        document.querySelectorAll(selector).forEach((element) => {
          element.remove();
          count += 1;
        });
      }
      return count;
    }, selectors);

    console.log(`Removed ${removed} element(s)`);
    await page.screenshot({ path: 'page.png', fullPage: true });
  } finally {
    await browser.close();
  }
})();

For a single combined selector, page.$$eval() is a concise alternative:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
await page.$$eval(
  '.cookie-banner, #newsletter-modal, .sticky-ad',
  (elements) => elements.forEach((element) => element.remove()),
);

await page.screenshot({ path: 'page.png' });

Use the selector API and waiting methods documented for the Puppeteer version installed in your project. The official Puppeteer documentation identifies the reviewed guides as version 25.12.0; API details may vary across versions.

Make the cleanup reliable on dynamic pages

Wait for the element or page state you actually need

Navigation completion does not necessarily mean that a consent dialog, delayed popup, or client-rendered widget is present—or that it has finished appearing. Pick a page-specific signal: for example, wait for a known content selector or the unwanted element itself. Then remove or hide it immediately before capture. The right condition depends on the target page; there is no universal readiness wait established by these APIs.

Keep selectors narrow and verify their matches

Selectors such as div, aside, or a broad shared class can match essential content or layout containers. Start with a selector specific to the unwanted element, inspect how many nodes it matches, and check the resulting screenshot. The examples return a removal count so a zero-match result is visible instead of silently assumed to have worked.

Account for reinsertion

Client-side scripts can insert an element after cleanup, or render a replacement before capture. If it returns, adjust the readiness condition and perform cleanup closer to the screenshot. For a screenshot-only requirement, Playwright’s injected CSS can be preferable because the rule applies during capture rather than depending on a one-time DOM mutation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Handle frames in the right context

A top-level document.querySelectorAll() searches the main document; it does not traverse iframe documents. For DOM removal inside an iframe, run evaluation against that frame’s document. Playwright’s screenshot style option is documented to apply to inner frames as well. Do not assume a page-level removal loop reaches content owned by a separate frame.

Capture only the element you need

If the output should contain one chart, card, or other component, capture that target directly rather than cleaning every obstruction on the page. For example, with Playwright:

await page.locator('.report-card').screenshot({ path: 'report-card.png' });

Puppeteer offers ElementHandle.screenshot() for a particular element. A targeted capture changes the scope of the screenshot; it is not a way to remove unwanted nodes from the page.

Troubleshooting common failures

  • The element still appears: it may have been inserted after your evaluation, the selector may not match it, or it may live in a frame. Wait for the page-specific state, verify the match count, run cleanup immediately before capture, or use Playwright screenshot CSS for capture-only hiding.
  • The main content disappears too: the selector is too broad. Inspect the matches and narrow it to a unique class, ID, or other page-specific selector before repeating the screenshot.
  • No element is removed: the element may not exist yet, the selector may be wrong, or the content may belong to another document such as an iframe. Wait for the actual element and evaluate in its frame when removing it.
  • A cookie notice returns after removal: page code likely rendered it again. Use a page-specific readiness signal and move cleanup nearer to capture; for a screenshot-only result in Playwright, consider the screenshot stylesheet.
  • The screenshot is blank or incomplete: verify that navigation reached the intended page and that your capture is taken after the required content is ready. DOM cleanup cannot compensate for a failed or premature page load.
  • You only need one component: use a locator or element-handle screenshot instead of capturing and cleaning the entire page.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean screenshot rather than controlling a local browser session, ScreenshotNeo provides a screenshot API and MCP server for developers. One GET request can return PNG, JPEG, WebP, or PDF. The API accepts familiar screenshot parameter names, which can make switching easier. Its cleanup can accept cookie or consent banners and remove 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, with the response identifying the page verdict and billing status in headers. The MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, or another MCP client.

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

Install the requests package if needed, then run this Python example, replacing the target URL and API key:

Best Value
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

See the ScreenshotNeo API documentation for request details. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan. Sign up free to get 1,000 screenshots a month with no card.

Performance, reliability, and cost considerations

Local Playwright or Puppeteer gives you control over browser lifecycle, page context, selector logic, and what happens before capture. That flexibility also means your code must manage browser startup, navigation, readiness, cleanup, and failures. Always close the browser in a finally block in scripts that may throw; otherwise a failed selector or navigation can leave a browser process running.

For a single page, removal and screenshot capture are straightforward. For changing pages, the main reliability cost is not the selector loop but knowing when the page has reached the state you intend to capture. A premature screenshot can miss content; an overly broad selector can erase it. Page-specific waits and match verification make these failure modes easier to diagnose. The reviewed official API documentation provides no benchmark or general timing guarantee, so performance depends on the target page, browser setup, network, and capture configuration.

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

A hosted screenshot API avoids writing browser-launch and cleanup code for each capture, but it changes the workflow: you send a request and consume the returned image or PDF. Choose based on whether you need direct browser control and custom page logic, or a simpler capture request with the service’s documented options.

Reference documentation

Frequently Asked Questions

Does removing a DOM element change the website for other visitors?

No. The evaluation changes the document in your automated browser page, not the website’s server content or another visitor’s session.

Can I remove an element from a cross-origin iframe with page.evaluate()?

Not by querying the top-level document. Run the evaluation in the iframe’s own frame context; top-level document queries do not traverse iframe documents.

Should I use CSS hiding or DOM removal for a screenshot?

Use CSS hiding when only the rendered screenshot should change and DOM removal when the page document itself should change. Playwright’s screenshot stylesheet provides the capture-only route.

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

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.