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).
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.
scrapy-playwright is available on PyPI and can be installed with pip:
pip install scrapy-playwrightplaywright 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 installIt's also possible to install only a subset of the available browsers:
playwright install firefox chromiumSee the changelog document.
Replace the default https and/or http Download Handlers through
DOWNLOAD_HANDLERS:
# 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.
Install the asyncio-based Twisted reactor:
# settings.py
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"This is the default in new projects since Scrapy 2.7.
Set the playwright Request.meta
key to download a request using Playwright:
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}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.
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.
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.:
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 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:
ProactorEventLoop supports subprocesses,
whereas SelectorEventLoop does not". Source:
Python docs.asyncio reactor requires the SelectorEventLoop. Source:
Twisted repositoryPLAYWRIGHT_BROWSER_TYPEType str, default "chromium".
The browser type to be launched, e.g. chromium, firefox, webkit.
PLAYWRIGHT_BROWSER_TYPE = "firefox"PLAYWRIGHT_LAUNCH_OPTIONSType 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.
PLAYWRIGHT_LAUNCH_OPTIONS = {
"headless": False,
"timeout": 20 * 1000, # 20 seconds
}PLAYWRIGHT_BROWSER_PROVIDERType 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.
PLAYWRIGHT_BROWSER_PROVIDER = "myproject.providers.CustomBrowserProvider"PLAYWRIGHT_CDP_URLType Optional[str], default None
The endpoint of a remote Chromium browser to connect using the
Chrome DevTools Protocol,
via BrowserType.connect_over_cdp.
PLAYWRIGHT_CDP_URL = "http://localhost:9222"If this setting is used:
PLAYWRIGHT_LAUNCH_OPTIONS setting is ignoredPLAYWRIGHT_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_KWARGSType 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.
PLAYWRIGHT_CDP_KWARGS = {
"slow_mo": 1000,
"timeout": 10 * 1000
}PLAYWRIGHT_CONNECT_URLType 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.launchServerin Node.js, the major and minor version needs to match the client version (1.2.3 → is compatible with 1.2.x).
PLAYWRIGHT_CONNECT_URL = "ws://localhost:35477/ae1fa0bc325adcfd9600d9f712e9c733"If this setting is used:
PLAYWRIGHT_LAUNCH_OPTIONS setting is ignoredThis settings CANNOT be used at the same time as PLAYWRIGHT_CDP_URL
PLAYWRIGHT_CONNECT_KWARGSType 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.
PLAYWRIGHT_CONNECT_KWARGS = {
"slow_mo": 1000,
"timeout": 10 * 1000
}PLAYWRIGHT_CONTEXTSType dict[str, dict], default {}
A dictionary which defines Browser contexts to be created on startup. It should be a mapping of (name, keyword arguments).
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_CONTEXTSType 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.
PLAYWRIGHT_MAX_CONTEXTS = 8PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUTType 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.
PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT = 10 * 1000 # 10 secondsPLAYWRIGHT_DOWNLOAD_TIMEOUTType 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.
PLAYWRIGHT_DOWNLOAD_TIMEOUT = 60000 # 1 minutePLAYWRIGHT_PROCESS_REQUEST_HEADERSType `O
No open issues yet, or sync has not completed.