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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Playwright Python can return different HTML in headed and headless runs because those runs may use different Chromium implementations, browser settings, environments, or capture times. The Python binding is rarely the root cause by itself. First verify the browser executable and channel; then make the context and readiness condition identical before comparing page.content().

What “different HTML” means in Playwright

page.content() serializes the page’s current document, including its doctype. It is a snapshot, not a promise of the final markup the application will produce. A difference may be in the initial server response, in DOM changes made by JavaScript, or simply in when each run took its snapshot.

Separate those cases before changing selectors or application code:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Different raw response: the server, proxy, cookies, user agent, locale, or other request conditions may have produced different source HTML.
  • Same response, different live DOM: hydration, client-side routing, data fetching, feature detection, or a failed script may have changed what is in the document.
  • Different capture moment: one run may have captured before a component appeared or changed.

Headed mode showing an element is useful evidence, but it does not prove that the headless run used the same browser binary, settings, operating system, or timing.

#1 Best Overall
Sale
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

Check the Chromium executable and channel first

Playwright documents a regular Chromium build for headed operation and a separate Chromium headless shell for the default headless operation. It also supports a newer headless implementation through the chromium channel. Consequently, headless=True and headless=False do not necessarily exercise identical browser implementations. The Playwright browser documentation describes the newer headless mode as closer to regular headed Chrome and distinguishes it from the default headless shell: Playwright: Browsers.

Check whether both runs use the same Playwright package version, browser type, channel, and executable. A local headed test might use installed Chrome via a branded channel, while CI headless uses Playwright’s bundled shell. That is a configuration difference, not a Python-specific HTML serialization bug.

If parity is important, pin the Playwright version, install the browser artifacts that version expects in both environments, and explicitly choose the intended channel. To investigate the newer headless implementation, compare a headless launch with channel="chromium" against your other configuration; do not assume it changes every other variable or guarantees identical results.

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

Make the browser context match

Browser context settings can affect responsive templates, localization, feature detection, permissions, and client-side branches. Playwright’s documented context options include viewport, user agent, locale, timezone, JavaScript, proxy, and permissions. Its default viewport is 1280 × 720 unless configured otherwise. See Playwright: Browser and Playwright: Emulation.

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

Set the same relevant values in each run rather than relying on defaults or a visible window’s dimensions:

  • Viewport and device emulation: normalize viewport, screen, device_scale_factor, is_mobile, and has_touch. A responsive site may render different components at different breakpoints.
  • Request identity: match user_agent, cookies, storage state, authentication, custom headers, proxy, and network mocks. A server may return different markup for different clients or sessions.
  • Locale and time: match locale and timezone_id when content, dates, or client-side formatting depend on them.
  • Browser capabilities: keep JavaScript, permissions, and any relevant media or device settings consistent. Available fonts, GPU support, and operating-system libraries can also affect feature detection or rendering.

With no_viewport, a headed window can be resized, whereas a headless run commonly keeps the context’s fixed viewport. An explicit context viewport makes the comparison easier to interpret.

Wait for the same application state before reading HTML

Navigation can wait for commit, domcontentloaded, load, or networkidle. These states describe browser or network lifecycle events; none necessarily means that a single-page application has finished hydrating, fetching data, or changing routes. Playwright discourages using networkidle as a general test-readiness signal and recommends assertions for the state the test actually needs. See Playwright: Page.

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

Wait for a meaningful, deterministic signal: a visible dashboard, a known data attribute, a test ID, or completion of a specific response. Avoid relying on an arbitrary wait_for_timeout() sleep in production tests; it may be too short on a slow run and wasteful on a fast one.

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.

Reproduce and compare both runs in Python

This synchronous example uses the same context options and application-ready assertion each time. Change only HEADLESS between runs. The example URL and app-ready test ID are illustrative; replace them with your target and a readiness signal that the application actually provides.

from playwright.sync_api import sync_playwright

URL = "https://example.test"
HEADLESS = True  # Repeat with False; change no other setting.

with sync_playwright() as p:
    browser = p.chromium.launch(headless=HEADLESS)
    context = browser.new_context(
        viewport={"width": 1280, "height": 720},
        locale="en-US",
        timezone_id="UTC",
        java_script_enabled=True,
    )
    page = context.new_page()

    page.goto(URL, wait_until="domcontentloaded")
    page.get_by_test_id("app-ready").wait_for(state="visible")

    html = page.content()
    print({
        "url": page.url,
        "user_agent": page.evaluate("navigator.userAgent"),
        "viewport": page.viewport_size,
        "html_length": len(html),
    })
    print(html)
    browser.close()

Run it with the same Playwright version, channel, environment, and context options in both cases. For closer diagnosis, record the browser version and launch options as well as the URL, user agent, locale, timezone, and viewport. Capture console errors, page errors, failed requests, and screenshots alongside the HTML. A screenshot can reveal a visible rendering difference, but it cannot by itself explain a markup difference.

When comparing serialized documents, normalize only values you know are dynamic, such as timestamps, request IDs, random IDs, or ad content. Do not normalize away the element or attribute whose presence you are investigating.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Isolate server HTML from JavaScript changes

Compare the raw response body with the live document returned by page.content(). If the raw HTML differs, investigate request conditions and server-side variation first. If raw HTML matches but the live DOM differs, investigate scripts, hydration, client-side data, runtime errors, and readiness timing.

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

Also inspect whether required requests failed in only one run. A blocked request, proxy difference, or environment-specific failure may leave the client without the data needed to create an element. Console and page errors can distinguish that from a selector problem.

Debugging checklist

  1. Confirm browser identity. Compare Playwright versions, browser type, channel, executable, and browser version. Check whether one run uses a branded Chrome or Edge channel and the other the bundled headless shell.
  2. Log context identity. Record navigator.userAgent, page.viewport_size, locale, timezone, and device-emulation options in each run.
  3. Fix the viewport explicitly. Use the same width and height; do not compare a resized headed window with an implicit headless viewport.
  4. Match state and traffic. Use equivalent cookies, storage state, authentication, permissions, proxy, request interception, and network mocks.
  5. Wait for the application, not a duration. Use an assertion for the element or state that must exist before calling page.content().
  6. Inspect errors and requests. Check console errors, page errors, and failed network requests for evidence of missing scripts or data.
  7. Compare source and live DOM. This tells you whether variation occurred in the response or after JavaScript ran.
  8. Test the newer headless option if useful. Try the chromium channel and document the choice, rather than treating all headless modes as interchangeable.

Troubleshooting common symptoms

Symptom Likely cause What to check or change
An element appears headed but is absent headless Different executable or channel, failed request/script, viewport breakpoint, or capture before hydration Compare browser identity and context settings, inspect errors and requests, and wait for an application-specific visible assertion.
The whole page has different markup Different server response, session, user agent, locale, proxy, or browser version Compare raw response bodies and normalize request, context, and browser configuration.
HTML differs only intermittently Timing or dynamic content such as IDs, timestamps, ads, and asynchronous updates Wait on a deterministic app condition and normalize only known variable fields before diffing.
Headed works locally but not in CI Different OS libraries, fonts, GPU availability, installed browser, network, or environment variables Treat CI and local machines as separate environments; compare their browser versions, dependencies, fonts, launch options, and failed requests.
The markup is initially similar, then diverges Hydration, client-side routing, or a later data fetch Wait for the route or data-driven element that matters, and inspect page errors and relevant response completion.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and reliability considerations

Adding a fixed delay can make a test slower without making it reliable: a slow CI run can still outlast the delay, while a fast run waits unnecessarily. A specific web assertion ties the wait to the condition under test. Keep captures comparable by holding browser version, channel, context, network behavior, and readiness constant; otherwise a changed HTML diff cannot be attributed to headed versus headless mode alone.

There is no universal percentage or frequency for headed/headless HTML divergence established by the documented mechanisms. Treat each discrepancy as a reproducibility problem and identify which comparison axis changed before concluding that headless mode caused it.

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.

Or skip the browser setup

If your goal is a clean image or PDF of a URL rather than debugging an application’s exact DOM, ScreenshotNeo offers a one-request screenshot API and an MCP server for AI agents. Its capture flow removes cookie/consent banners, newsletter popups, and chat widgets before the shot; those cleanup steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. AI agents can use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf.

For a quick capture, replace the target URL and API key. The API returns an image or PDF according to the requested options; see the ScreenshotNeo API documentation for formats, parameters, and setup.

Best Value
Sale
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.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://example.com 
  -o shot.webp

The free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000. This is an alternative for screenshot capture, not a substitute for matching Playwright environments when your test needs to inspect or compare the DOM. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does Playwright Python itself change the HTML between headed and headless runs?

Not usually by itself. The browser executable or channel, context, environment, network responses, and capture timing are the first variables to compare.

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

Does setting `headless=False` guarantee the same DOM as headless mode?

No. Headed and headless runs can use different Chromium implementations and may still differ in settings, machine environment, or readiness timing.

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.