Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

scrapy-playwright

> DevOps
Open source

Playwright integration for Scrapy

1.4K stars0 likes0 views
WebsiteGitHub

About

Playwright integration for Scrapy

scrapy-playwright: Playwright integration for Scrapy

A Scrapy Download Handler which performs requests using Playwright for Python. It can be used to handle pages that require JavaScript (among other things), while adhering to the regular Scrapy workflow (i.e. without interfering with request scheduling, item processing, etc).

Requirements

After the release of version 2.0, which includes coroutine syntax support and asyncio support, Scrapy allows to integrate asyncio-based projects such as Playwright.

Minimum required versions

  • Python >= 3.10
  • Scrapy >= 2.7
  • Playwright >= 1.40

Installation

scrapy-playwright is available on PyPI and can be installed with pip:

bash
pip install scrapy-playwright

playwright is defined as a dependency so it gets installed automatically, however it might be necessary to install the specific browser(s) that will be used:

playwright install

It's also possible to install only a subset of the available browsers:

playwright install firefox chromium

Changelog

See the changelog document.

Activation

Download handler

Replace the default https and/or http Download Handlers through DOWNLOAD_HANDLERS:

python
# settings.py
DOWNLOAD_HANDLERS = {
    "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    # "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}

Registering the handler for https is usually enough, since most modern sites use HTTPS. Enable the http handler only if you need to process plain HTTP URLs with Playwright.

Note that the ScrapyPlaywrightDownloadHandler class inherits from the default http/https handler. Unless explicitly marked (see Basic usage), requests will be processed by the regular Scrapy download handler.

Twisted reactor

Install the asyncio-based Twisted reactor:

python
# settings.py
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"

This is the default in new projects since Scrapy 2.7.

Basic usage

Set the playwright Request.meta key to download a request using Playwright:

python
import scrapy

class AwesomeSpider(scrapy.Spider):
    name = "awesome"

    async def start(self):  # start_requests in Scrapy < 2.13
        # GET request
        yield scrapy.Request("https://httpbin.org/get", meta={"playwright": True})
        # POST request
        yield scrapy.FormRequest(
            url="https://httpbin.org/post",
            formdata={"foo": "bar"},
            meta={"playwright": True},
        )

    def parse(self, response, **kwargs):
        # 'response' contains the page as seen by the browser
        return {"url": response.url}

About the start/start_requests methods

Scrapy 2.13 introduced the async start() -> AsyncIterator Spider method and deprecated the traditional start_requests method. Support for the latter was removed in Scrapy 2.16. For simplicity, the rest of the examples in this Readme will use start, replace async def start with def start_requests if you are using an older Scrapy version.

About the User-Agent header

By default, outgoing requests include the User-Agent set by Scrapy (either with the USER_AGENT or DEFAULT_REQUEST_HEADERS settings or via the Request.headers attribute). This could cause some sites to react in unexpected ways, for instance if the user agent does not match the running Browser. If you prefer the User-Agent sent by default by the specific browser you're using, set the Scrapy user agent to None.

About the response body and type

The body of a Playwright response is the serialized DOM of the page, as rendered by the browser. Browsers wrap non-HTML content in HTML tags of their own: a JSON document is usually displayed inside a <pre> tag, sometimes along with viewer-specific markup. Because of that, responses are HTML (scrapy.http.HtmlResponse) regardless of the Content-Type header reported by the server, and the body of a request to a JSON endpoint cannot be parsed directly with Response.json or Response.jmespath. Extract the text node first, e.g.:

python
import json

def parse(self, response, **kwargs):
    data = json.loads(response.css("pre::text").get())

This does not apply to downloads, which keep the bytes and the type of the downloaded file.

Windows support

Windows support is possible by running Playwright in a ProactorEventLoop in a separate thread. This is necessary because it's not possible to run Playwright in the same asyncio event loop as the Scrapy crawler:

  • Playwright runs the driver in a subprocess. Source: Playwright repository.
  • "On Windows, the default event loop ProactorEventLoop supports subprocesses, whereas SelectorEventLoop does not". Source: Python docs.
  • Twisted's asyncio reactor requires the SelectorEventLoop. Source: Twisted repository

Supported settings

PLAYWRIGHT_BROWSER_TYPE

Type str, default "chromium".

The browser type to be launched, e.g. chromium, firefox, webkit.

python
PLAYWRIGHT_BROWSER_TYPE = "firefox"

PLAYWRIGHT_LAUNCH_OPTIONS

Type dict, default {}

A dictionary with options to be passed as keyword arguments when launching the Browser. See the docs for BrowserType.launch for a list of supported keyword arguments.

python
PLAYWRIGHT_LAUNCH_OPTIONS = {
    "headless": False,
    "timeout": 20 * 1000,  # 20 seconds
}

PLAYWRIGHT_BROWSER_PROVIDER

Type str or type, default "scrapy_playwright.provider.PlaywrightBrowserProvider"

A class that owns the browser lifecycle (startup, launching/connecting browsers, optional persistent contexts, teardown). The value might be either an import path string or the provider class itself. The provider is instantiated with the handler configuration object as argument.

The default provider wraps vanilla Playwright and supports everything documented in this README (local launch, PLAYWRIGHT_CDP_URL, PLAYWRIGHT_CONNECT_URL, persistent contexts, etc). This is an extension point for integrating third-party drivers that expose Playwright-compatible Browser/BrowserContext/Page objects (e.g. patchright, camoufox) without changing the handler. See docs/pluggable-browser-providers.md for the interface and ready-made example providers.

python
PLAYWRIGHT_BROWSER_PROVIDER = "myproject.providers.CustomBrowserProvider"

PLAYWRIGHT_CDP_URL

Type Optional[str], default None

The endpoint of a remote Chromium browser to connect using the Chrome DevTools Protocol, via BrowserType.connect_over_cdp.

python
PLAYWRIGHT_CDP_URL = "http://localhost:9222"

If this setting is used:

  • all non-persistent contexts will be created on the connected remote browser
  • the PLAYWRIGHT_LAUNCH_OPTIONS setting is ignored
  • the PLAYWRIGHT_BROWSER_TYPE setting must not be set to a value different than "chromium"

This settings CANNOT be used at the same time as PLAYWRIGHT_CONNECT_URL

PLAYWRIGHT_CDP_KWARGS

Type dict[str, Any], default {}

Additional keyword arguments to be passed to BrowserType.connect_over_cdp when using PLAYWRIGHT_CDP_URL. The endpoint_url key is always ignored, PLAYWRIGHT_CDP_URL is used instead.

python
PLAYWRIGHT_CDP_KWARGS = {
    "slow_mo": 1000,
    "timeout": 10 * 1000
}

PLAYWRIGHT_CONNECT_URL

Type Optional[str], default None

URL of a remote Playwright browser instance to connect using BrowserType.connect.

From the upstream Playwright docs:

When connecting to another browser launched via BrowserType.launchServer in Node.js, the major and minor version needs to match the client version (1.2.3 → is compatible with 1.2.x).

python
PLAYWRIGHT_CONNECT_URL = "ws://localhost:35477/ae1fa0bc325adcfd9600d9f712e9c733"

If this setting is used:

  • all non-persistent contexts will be created on the connected remote browser
  • the PLAYWRIGHT_LAUNCH_OPTIONS setting is ignored

This settings CANNOT be used at the same time as PLAYWRIGHT_CDP_URL

PLAYWRIGHT_CONNECT_KWARGS

Type dict[str, Any], default {}

Additional keyword arguments to be passed to BrowserType.connect when using PLAYWRIGHT_CONNECT_URL. The ws_endpoint key is always ignored, PLAYWRIGHT_CONNECT_URL is used instead.

python
PLAYWRIGHT_CONNECT_KWARGS = {
    "slow_mo": 1000,
    "timeout": 10 * 1000
}

PLAYWRIGHT_CONTEXTS

Type dict[str, dict], default {}

A dictionary which defines Browser contexts to be created on startup. It should be a mapping of (name, keyword arguments).

python
PLAYWRIGHT_CONTEXTS = {
    "foobar": {
        "context_arg1": "value",
        "context_arg2": "value",
    },
    "default": {
        "context_arg1": "value",
        "context_arg2": "value",
    },
    "persistent": {
        "user_data_dir": "/path/to/dir",  # will be a persistent context
        "context_arg1": "value",
    },
}

See the section on browser contexts for more information. See also the docs for Browser.new_context.

PLAYWRIGHT_MAX_CONTEXTS

Type Optional[int], default None

Maximum amount of allowed concurrent Playwright contexts. If unset or None, no limit is enforced. See the Maximum concurrent context count section for more information.

python
PLAYWRIGHT_MAX_CONTEXTS = 8

PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT

Type Optional[float], default None

Timeout to be used when requesting pages by Playwright, in milliseconds. If None or unset, the default value will be used (30000 ms at the time of writing). See the docs for BrowserContext.set_default_navigation_timeout.

python
PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT = 10 * 1000  # 10 seconds

PLAYWRIGHT_DOWNLOAD_TIMEOUT

Type int, default 30000 (30 seconds)

Timeout in milliseconds to wait for a file download to start and to finish. If the timeout is exceeded, the original navigation error is re-raised instead of hanging indefinitely.

python
PLAYWRIGHT_DOWNLOAD_TIMEOUT = 60000  # 1 minute

PLAYWRIGHT_PROCESS_REQUEST_HEADERS

Type `O

Issues· 15 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonchrome-headlessfirefox-headlesshacktoberfestheadless-browser

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理