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.

A Pyppeteer error such as “connection unexpectedly closed,” “WebSocket connection is closed,” “Websocket connection is lost,” or “Target closed” means that the browser-control connection or the page target disappeared while your code was waiting for it. It is a symptom, not a single diagnosis. Start by checking Chromium compatibility, then prove that your code is not closing a browser or page too early, inspect dependency and cancellation behavior, and finally reduce the crawler to one page with browser diagnostics enabled.

What the error actually means

Pyppeteer controls Chromium through a DevTools WebSocket. Your Python code sends commands such as newPage(), goto() and close() over that connection. Each page is a browser target. If Chromium exits, the WebSocket disconnects, or the page target is closed while an operation is pending, the pending coroutine can raise a connection-closed or target-closed exception.

The same wording appears in different situations: a browser launched with an incompatible executable, an attached browser whose endpoint is no longer valid, a finally block that closes a shared browser, a task canceled during navigation, or a dependency interaction. Therefore, do not begin by applying a random timeout or package pin. Collect runtime details and isolate one variable at a time.

Run a minimal diagnostic crawler first

Use one browser, one page and a stable URL. This separates Pyppeteer from queueing, proxy, retry and concurrency code.

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.
import asyncio
import logging
import platform
import sys

from pyppeteer import launch
import pyppeteer
import websockets

async def main():
    print("Python:", sys.version)
    print("Platform:", platform.platform())
    print("Pyppeteer:", getattr(pyppeteer, "__version__", "unknown"))
    print("websockets:", getattr(websockets, "__version__", "unknown"))

    browser = await launch(
        headless=True,
        dumpio=True,
        handleSIGINT=False,
        handleSIGTERM=False,
        handleSIGHUP=False,
    )
    try:
        page = await browser.newPage()
        await page.goto("https://example.com", {"waitUntil": "networkidle2", "timeout": 60000})
        print("title:", await page.title())
    finally:
        await browser.close()

asyncio.run(main())

dumpio=True forwards Chromium’s stderr to your process. Keep the complete traceback and stderr, along with the Python, Pyppeteer, Chromium and websockets versions. If this script fails, the problem is probably environment or compatibility related. If it succeeds, add your crawler’s behavior back gradually.

Check Chromium and Pyppeteer compatibility

Test the bundled browser

Pyppeteer’s API documentation says it works best with its bundled Chromium and warns, “There is no guarantee it will work with any other version.” The documentation is legacy material, so verify syntax and defaults against the version installed in your environment, but treat the compatibility warning seriously.

If your code supplies executablePath, remove only that setting and repeat the minimal script. Record both results. A failure with the external executable and success with the bundled browser is strong evidence of a browser-version mismatch. Do not change Python, concurrency and the executable path in the same experiment.

# External browser: test only when you have a reason to override Chromium
browser = await launch(executablePath="/absolute/path/to/chromium", dumpio=True)

# Comparison run: allow Pyppeteer to use its bundled Chromium
browser = await launch(dumpio=True)

Check launch versus connect mode

Log whether you call launch() or connect(). With connect(), confirm that the configured browserWSEndpoint is current and reachable at the time of the call. An endpoint copied from a previous browser process, a container that has restarted, or a port that is not exposed will produce connection failures before page work can complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.
browser = await pyppeteer.connect(
    browserWSEndpoint="ws://127.0.0.1:9222/devtools/browser/your-current-id"
)

For an attached browser, the process owner is outside your script. Make sure that service does not terminate or recycle Chromium while your crawl is running.

Find premature browser, page or context closure

Audit every close path

Search for browser.close(), browser.disconnect(), page.close(), context closure and cancellation handlers. A common failure is a helper that owns a shared browser and closes it in finally while another task is still navigating. The exception may surface in newPage(), goto() or a later selector operation, making the original close hard to spot.

  • Give the browser one explicit owner.
  • Keep that owner alive until every page task has been awaited.
  • Give each task a page it owns, or protect shared-page use with a lock.
  • Close pages after their work, not while another coroutine is using them.
  • Call disconnect() only when you intentionally leave an externally managed browser running; call close() when your process owns the browser.

Use structured task ownership

async def crawl(urls):
    browser = await launch(dumpio=True)
    try:
        pages = await asyncio.gather(
            *(crawl_one(browser, url) for url in urls),
            return_exceptions=False,
        )
        return pages
    finally:
        # This runs only after gather() has completed or failed.
        await browser.close()

async def crawl_one(browser, url):
    page = await browser.newPage()
    try:
        await page.goto(url, {"waitUntil": "domcontentloaded", "timeout": 60000})
        return await page.title()
    finally:
        await page.close()

If one task fails, gather() and your cancellation policy determine whether sibling tasks continue. Decide that policy explicitly; do not let an exception handler close a shared browser as an accidental side effect.

Investigate timeouts and cancellation

A timeout is not automatically the cause. However, one historical report made WebSocket loss reproducible by wrapping navigation in a short asyncio.wait_for. Cancellation can interrupt a navigation while other tasks still use the same page or browser.

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.

Temporarily remove the outer cancellation

# Diagnostic run: let Pyppeteer’s navigation timeout report the failure
await page.goto(url, {"waitUntil": "networkidle2", "timeout": 60000})

# Only after the baseline works, add an outer deadline
await asyncio.wait_for(
    page.goto(url, {"waitUntil": "domcontentloaded", "timeout": 60000}),
    timeout=90,
)

Lengthen both deadlines for slow pages and log which one fired. If an outer timeout cancels a task, stop using that page until its cancellation has completed, or discard the page and create a new one. Do not continue issuing commands to a page whose navigation coroutine was forcibly canceled.

Separate pages under concurrency

For a diagnostic run, use one page. Then restore concurrency in small steps. If one page works and ten pages fail, inspect shared-page access, task cancellation and resource pressure before changing browser flags.

Inspect dependency compatibility

Record the installed Pyppeteer and websockets versions in the failing environment and in a clean virtual environment. A historical issue associated WebSocket loss with a websockets 7.0 upgrade. That report is anecdotal and old; it is a lead for a controlled comparison, not a universal recommendation to pin that version.

  1. Create a clean environment with the same Python version.
  2. Install the exact versions used by the crawler.
  3. Run the one-page script.
  4. Change only the suspected dependency and repeat.
  5. Keep the version that is compatible with your installed Pyppeteer and Python, and document the tested combination.

Do not blindly copy an old pin into a current deployment. Pyppeteer is an unofficial port of Puppeteer, not the official Python package maintained by the Puppeteer project. Its repository points users to Puppeteer documentation and troubleshooting material, but package behavior still depends on the versions you actually install.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Capture useful browser diagnostics

  • Set dumpio=True during reproduction and save Chromium stderr.
  • Enable Python logging at debug level for the failing run.
  • Save the complete traceback, including the first exception rather than only the final “Target closed” line.
  • Record operating system or container details, launch versus connect mode, executable path, browser version, Pyppeteer version, Python version and websockets version.
  • Note whether the failure happens at browser launch, newPage(), navigation, selector waits or page evaluation.

These details distinguish an unreachable endpoint from a browser exit and a canceled page operation.

Reduce and restore the crawler safely

  1. Use a stable URL and one page.
  2. Run with bundled Chromium and diagnostics enabled.
  3. Remove outer wait_for cancellation and use a generous navigation timeout.
  4. Confirm that the page can navigate and close cleanly.
  5. Add your real URL, then cookies, headers, proxies and JavaScript.
  6. Increase concurrency one step at a time.
  7. After each change, retain the versions and logs for that run.

If the minimal script succeeds but the full crawler fails, the cause is in a restored behavior: lifecycle ownership, cancellation, a shared page, a request interception handler, or an environment-specific browser process. A minimal reproduction is also the most useful format when asking for help.

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

Common symptoms and targeted fixes

Symptom Likely lead Isolated test
Error during browser.newPage() Browser process or WebSocket already closed; premature close; incompatible executable Run one page with bundled Chromium, dumpio=True, and no concurrent tasks
Failure during goto() Navigation cancellation, short timeout, browser exit or unstable target Remove outer wait_for, lengthen navigation timeout, and inspect stderr
Works alone but fails under load Shared-page use, task cancellation or lifecycle race Give each task its own page and increase concurrency gradually
connect() fails immediately Stale or unreachable browser WebSocket endpoint Verify the current endpoint and the process that owns Chromium
Only an overridden executable fails Chromium/Pyppeteer compatibility Remove executablePath and compare with bundled Chromium

Or skip the browser setup

If your goal is simply to obtain reliable website screenshots rather than maintain a Chromium crawler, ScreenshotNeo provides a single HTTP request. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and each response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

See the ScreenshotNeo API documentation for options and authentication.

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

cURL

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)
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}`);

Every feature is included on every plan. The Free plan provides 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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.

When to ask for help

If compatibility, lifecycle, cancellation and dependency tests do not isolate the failure, provide the exact package and browser versions, operating system or container details, launch or connect mode, browser stderr and a minimal script. State where the exception occurs and whether bundled Chromium changes the result. Avoid claiming that headful mode, a particular timeout or one historical dependency version is universally responsible: the available issue reports are context-specific and do not establish a current compatibility matrix.

Frequently Asked Questions

Does “Target closed” always mean the website blocked my crawler?

No. It only says that the page target disappeared before the pending operation finished. Browser shutdown, an explicit page close, cancellation and compatibility problems can all produce it.

Should I switch to headful mode to fix the error?

Not as a first-line fix. A 2023 report recorded the error in headful mode, but that report does not show that headful mode itself causes the failure. Compare launch settings while keeping the other variables unchanged.

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

What information should a bug report include?

Include Python, Pyppeteer, Chromium and websockets versions; operating system or container details; launch versus connect mode; executable path; complete traceback; Chromium stderr; and a minimal one-page reproduction.

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.