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

Use Chrome’s DevTools Protocol (CDP) to emulate prefers-color-scheme: dark before loading the page, then call Selenium’s screenshot method. The emulation changes the page’s media-query preference; Selenium still performs the actual capture. If you change the preference after navigation, reload before taking the screenshot.

What the workflow does

A dark screenshot requires two separate operations:

  1. Tell Chromium that the user prefers a dark color scheme with Emulation.setEmulatedMedia.
  2. Capture the rendered page with Selenium, such as save_screenshot() or an element’s screenshot() method.

This procedure activates a site’s own dark theme when it responds to the CSS prefers-color-scheme media feature. It does not automatically force every page to darken.

Prerequisites and version notes

  • Python 3 and an installed Selenium package.
  • Google Chrome or another Chromium browser that matches the driver Selenium starts.
  • A page that has a dark style tied to prefers-color-scheme, or a known selector/style you can use to verify the result.

Install Selenium in the environment that will run the script:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
python -m pip install -U selenium

Selenium’s CDP integration is Chromium-specific and version-sensitive. Selenium documents CDP as a temporary bridge while WebDriver BiDi is implemented, and warns that CDP functionality depends heavily on the browser version. Pin and test compatible browser and Selenium versions in continuous-integration jobs rather than assuming that a command that worked last year will remain unchanged.

Complete Python example

The following script applies the emulation before navigation, captures the page, and always closes the browser:

from selenium import webdriver

options = webdriver.ChromeOptions()
# Uncomment for a server without a visible desktop:
# options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)

try:
    driver.execute_cdp_cmd(
        "Emulation.setEmulatedMedia",
        {
            "features": [
                {"name": "prefers-color-scheme", "value": "dark"}
            ]
        },
    )
    driver.get("https://example.com")
    driver.save_screenshot("dark-mode.png")
finally:
    driver.quit()

The call to execute_cdp_cmd is Selenium’s Python binding for sending a CDP command. The features array names the media feature and supplies the value dark. Replace the example URL with the page under test.

If the page is already open

When a test changes the emulation after navigation, reload the document before capturing it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
driver.execute_cdp_cmd(
    "Emulation.setEmulatedMedia",
    {"features": [{"name": "prefers-color-scheme", "value": "dark"}]},
)
driver.refresh()
driver.save_screenshot("dark-mode-after-refresh.png")

Reloading gives the page a chance to reevaluate its media queries and theme initialization code.

Wait for the dark UI before capturing

A screenshot taken immediately after navigation can catch a loading shell, an animation, or a theme switch that has not finished. Wait for a stable, page-specific condition instead of using a large fixed sleep whenever possible.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Wait for a theme indicator

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

# Example: the application adds this class when dark styling is active.
WebDriverWait(driver, 15).until(
    lambda d: "dark" in d.find_element(By.TAG_NAME, "body").get_attribute("class")
)
driver.save_screenshot("dark-mode.png")

Change the condition to match the application’s real markup. A site may use a data attribute, a class on the document element, or only CSS variables.

Use a short delay only when necessary

import time

time.sleep(1)
driver.save_screenshot("dark-mode.png")

A delay is simple but less reliable than waiting for a selector or state. Keep it as a fallback for pages whose readiness cannot be expressed through the DOM.

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

Verify that the screenshot is actually dark

A successful screenshot call proves that Selenium wrote an image; it does not prove that the intended theme was applied. Add an assertion that is meaningful for your site.

Inspect a computed style

background = driver.execute_script(
    "return getComputedStyle(document.body).backgroundColor;"
)
print("body background:", background)
assert background not in ("rgb(255, 255, 255)", "rgba(0, 0, 0, 0)")

Choose a property whose expected dark value is stable in your application. Exact colors differ between designs, so do not copy the example assertion without checking your page.

Check a theme marker

theme = driver.execute_script(
    "return document.documentElement.getAttribute('data-theme');"
)
assert theme == "dark", f"Unexpected theme: {theme!r}"

If the site exposes no marker, compare a known region or inspect a computed CSS custom property. Keep this verification separate from the screenshot assertion so a light capture cannot silently become a passing fixture.

Capture a single component instead of the whole page

Selenium also provides element screenshot APIs. Locate the component after the page has switched themes, then save only that element:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
from selenium.webdriver.common.by import By

card = driver.find_element(By.CSS_SELECTOR, "main .pricing-card")
card.screenshot("dark-card.png")

Element capture is useful for a component regression test or a small visual artifact. Use driver.save_screenshot() when the browser viewport, including surrounding layout, is what you need to inspect.

Site dark theme versus automatic browser darkening

Emulated prefers-color-scheme

The Python example tests the site’s supported dark mode. A page can respond with CSS such as @media (prefers-color-scheme: dark), JavaScript theme selection, or both. This is generally the right condition for a dark-theme visual regression test because it exercises the design the site intended to provide.

Automatic dark rendering

Chrome also has an automatic dark-rendering mode that transforms web content even when the site has not implemented a dark theme. That is a different test condition from advertising a dark preference to the page. Use the CDP automatic-dark override only when your requirement is to test that browser transformation; do not substitute it for a site-theme test. The command and parameters can vary with the Chrome/CDP version, so verify the current protocol support before building a long-lived test around it.

Full-page, viewport, and layout considerations

A normal page screenshot represents the current browser viewport. Set the window size before navigation when a breakpoint matters:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
driver.set_window_size(1440, 1000)
driver.get("https://example.com")
driver.save_screenshot("desktop-dark.png")

Run another capture at a mobile-sized viewport if responsive dark styling is part of the requirement. Keep viewport dimensions, device-pixel settings, fonts, and browser version consistent across visual-regression runs; otherwise a color change can be obscured by layout or rendering differences.

For a long document, decide whether the test needs the viewport, a particular element, or a browser-specific full-page facility. Do not assume that a viewport screenshot includes content below the fold. If you use a full-page technique supplied by your Selenium/browser combination, test it separately because support and behavior are browser-dependent.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Troubleshooting dark Selenium screenshots

The image is still light

  • Confirm that the CDP command ran before get(), or call refresh() after changing it.
  • Check that the page actually implements prefers-color-scheme. A manual theme toggle may use application state instead of the media feature.
  • Verify a marker or computed style before saving; the screenshot method itself does not turn on dark mode.
  • Look for an iframe. The visible content may come from a separately rendered frame whose theme logic differs from the top document.

unknown command or an invalid-parameter error

CDP commands are tied to Chromium’s protocol implementation. Update or align Chrome, the driver, and Selenium, then check the command spelling and the features object. Avoid silently falling back to a light screenshot when the emulation call fails; fail the test and report the browser versions.

The screenshot is blank or shows a loading page

  • Wait for a page-specific selector or theme state.
  • Check network failures and JavaScript errors in the test environment.
  • For headless runs, use a realistic window size and ensure required fonts and assets are available.
  • Capture after the application’s route transition, not merely after the initial document load.

The screenshot differs between machines

Normalize browser version, viewport, device scale, installed fonts, locale, timezone, and animations. Disable or wait for transitions where your test permits it. A color-scheme preference does not eliminate other rendering variables.

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

The element screenshot fails

Wait until the element exists and is displayed, scroll it into view if needed, and make sure the selector identifies one intended component. A stale element reference means the framework replaced the node after you located it; find it again after the update.

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

Reliability and maintenance

Keep the CDP boundary small

Wrap the emulation call in one helper and record the browser and Selenium versions in test logs. This makes a protocol change easier to diagnose and limits the number of tests coupled directly to CDP.

Prefer deterministic readiness checks

Wait for the application’s dark-state marker, fonts, and data required for the screenshot. Fixed sleeps can pass on a fast workstation and fail on a busy CI runner.

Store useful failure artifacts

When an assertion fails, retain the screenshot, the current URL, and the detected theme marker. Those artifacts distinguish a failed color switch from a navigation, selector, or layout problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Browser compatibility and WebDriver BiDi

The documented route here is Chrome/Chromium CDP. CDP is not a stable, cross-browser testing API, and Selenium describes its access as temporary while WebDriver BiDi becomes available. BiDi is the W3C-standard direction for cross-browser automation, but an equivalent, universally available media-emulation command is not established by the documentation covered here. Treat CDP as the known Chrome solution, and verify current BiDi support before planning a migration.

Or skip the browser setup

ScreenshotNeo provides a hosted screenshot API and MCP server, so you can request an image without maintaining Chrome and Selenium. It can request dark-mode rendering, full-page captures, element selectors, custom viewport/device settings, waits, and custom CSS or JavaScript. Before capture it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

cURL

See the ScreenshotNeo API documentation for authentication and options.

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

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

Plans and cost

Plan Included screenshots Price
Free 1,000 per month Free; no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month—no card required.

Frequently Asked Questions

Can I use the same Selenium script to test a manual dark-mode toggle?

Yes, but that is a separate condition: perform the application’s documented toggle action, wait for its state marker, and then capture. The CDP preference test covers only behavior driven by the page’s color-scheme preference.

Does changing the preference persist for later browser sessions?

No. Apply the emulation in each new WebDriver session before the navigation that needs it.

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.

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.