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).
scrapy-playwright is available on PyPI and can be installed with pip:
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:
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.
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.
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:
The browser type to be launched, e.g. chromium, firefox, webkit.
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.
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.
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.
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).
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.
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 = 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.
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 minute
PLAYWRIGHT_PROCESS_REQUEST_HEADERS
Type Optional[Union[Callable, str]], default scrapy_playwright.headers.use_scrapy_headers
A function (or the path to a function) that processes a Playwright request and returns a
dictionary with headers to be overridden (note that, depending on the browser, additional
default headers could be sent as well). Coroutine functions (async def) are supported.
This will be called at least once for each Scrapy request, but it could be called additional times
if Playwright generates more requests (e.g. to retrieve assets like images or scripts).
The function must return a Dict[str, str] object, and receives the following three keyword arguments:
The default function (scrapy_playwright.headers.use_scrapy_headers) tries to
emulate Scrapy's behaviour for navigation requests, i.e. overriding headers
with their values from the Scrapy request. For non-navigation requests (e.g.
images, stylesheets, scripts, etc), only the User-Agent header is overriden,
for consistency.
Setting PLAYWRIGHT_PROCESS_REQUEST_HEADERS=None will give complete control to
Playwright, i.e. headers from Scrapy requests will be ignored and only headers
set by Playwright will be sent. Keep in mind that in this case, headers passed
via the Request.headers attribute or set by Scrapy components are ignored
(including cookies set via the Request.cookies attribute).
Whether the browser will be restarted if it gets disconnected, for instance if the local
browser crashes or a remote connection times out.
Implemented by listening to the
disconnected Browser event,
for this reason it does not apply to persistent contexts since
BrowserType.launch_persistent_context
returns the context directly.
PLAYWRIGHT_MAX_PAGES_PER_CONTEXT
Type int, defaults to the value of Scrapy's CONCURRENT_REQUESTS setting
A predicate function (or the path to a function) that receives a
playwright.async_api.Request
object and must return True if the request should be aborted, False otherwise.
Coroutine functions (async def) are supported.
Note that all requests will appear in the DEBUG level logs, however there will
be no corresponding response log lines for aborted requests. Aborted requests
are counted in the playwright/request_count/aborted job stats item.
def should_abort_request(request):
return (
request.resource_type == "image"
or ".jpg" in request.url
)
PLAYWRIGHT_ABORT_REQUEST = should_abort_request
A dictionary with keyword arguments to be used when creating a new context, if a context
with the name specified in the playwright_context meta key does not exist already.
See the section on browser contexts for more information.
If True, the Playwright page
that was used to download the request will be available in the callback at
response.meta['playwright_page']. If False (or unset) the page will be
closed immediately after processing the request.
Important!
This meta key is entirely optional, it's NOT necessary for the page to load or for any
asynchronous operation to be performed (specifically, it's NOT necessary for PageMethod
objects to be applied). Use it only if you need access to the Page object in the callback
that handles the response.
A dictionary of handlers to be attached to page events.
See Handling page events.
playwright_page_init_callback
Type Optional[Union[Callable, str]], default None
A coroutine function (async def) to be invoked for newly created pages.
Called after attaching page event handlers & setting up internal route
handling, before making any request. It receives the Playwright page and the
Scrapy request as positional arguments. Useful for initialization code.
Ignored if the page for the request already exists (e.g. by passing
playwright_page).
Type Optional[playwright.async_api.Page], default None
A Playwright page to be used to
download the request. If unspecified, a new page is created for each request.
This key could be used in conjunction with playwright_include_page to make a chain of
requests using the same page. For instance:
A dictionary with keyword arguments to be passed to the page's
goto method
when navigating to an URL. The url key is ignored if present, the request
URL is used instead.
A dictionary with security information
about the give response. Only available for HTTPS requests. Could be accessed
in the callback via response.meta['playwright_security_details']
The value of the Download.suggested_filename
attribute when the response is the binary contents of a
download (e.g. a PDF file).
Only available for responses that only caused a download. Can be accessed
in the callback via response.meta['playwright_suggested_filename']
Specifying a value that evaluates to True in the
playwright_include_page meta key for a
request will result in the corresponding playwright.async_api.Page object
being available in the playwright_page meta key in the request callback.
In order to be able to await coroutines on the provided Page object,
the callback needs to be defined as a coroutine function (async def).
Caution
Use this carefully, and only if you really need to do things with the Page
object in the callback. If pages are not properly closed after they are no longer
necessary the spider job could get stuck because of the limit set by the
PLAYWRIGHT_MAX_PAGES_PER_CONTEXT setting.
When passing playwright_include_page=True, make sure pages are always closed
when they are no longer used. It's recommended to set a Request errback to make
sure pages are closed even if a request fails (if playwright_include_page=False
pages are automatically closed upon encountering an exception).
This is important, as open pages count towards the limit set by
PLAYWRIGHT_MAX_PAGES_PER_CONTEXT and crawls could freeze if the limit is reached
and pages remain open indefinitely.
Defining callbacks as async def is only necessary if you need to await things,
it's NOT necessary if you just need to pass over the Page object from one callback
to another (see the example above).
Any network operations resulting from awaiting a coroutine on a Page object
(goto, go_back, etc) will be executed directly by Playwright, bypassing the
Scrapy request workflow (Scheduler, Middlewares, etc).
If a request does not explicitly indicate a context via the playwright_context
meta key, it falls back to using a general context called default. This default
context can also be customized on startup via the PLAYWRIGHT_CONTEXTS setting.
Note that persistent contexts are launched independently from the main browser
instance, hence keyword arguments passed in the
PLAYWRIGHT_LAUNCH_OPTIONS
setting do not apply.
Important: when ScrapyPlaywrightDownloadHandler is registered for both
http and https schemes, Scrapy creates one independent
handler instance per scheme. Both instances read the same PLAYWRIGHT_CONTEXTS
setting and will each try to open the same user_data_dir, which causes an
error because the browser only allows one process per profile directory.
To avoid this, make every user_data_dir value unique across handler
instances — for example by including a random suffix:
If the context specified in the playwright_context meta key does not exist, it will be created.
You can specify keyword arguments to be passed to
Browser.new_context
in the playwright_context_kwargs meta key:
Avoid race conditions & memory leaks when closing contexts
Make sure to close the page before closing the context. See
this comment
in #191
for more information.
Maximum concurrent context count
Specify a value for the PLAYWRIGHT_MAX_CONTEXTS setting to limit the amount
of concurent contexts. Use with caution: it's possible to block the whole crawl
if contexts are not closed after they are no longer used (refer to
this section to dinamically close contexts).
Make sure to define an errback to still close contexts even if there are errors.
Proxy support
Proxies are supported at the Browser level by specifying the proxy key in
the PLAYWRIGHT_LAUNCH_OPTIONS setting:
A sorted iterable (e.g. list, tuple, dict) of PageMethod objects
could be passed in the playwright_page_methodsRequest.meta
key to request methods to be invoked on the Page object before returning the final
Response to the callback.
This is useful when you need to perform certain actions on a page (like scrolling
down or clicking links) and you want to handle only the final result in your callback.
Represents a method to be called (and awaited if necessary) on a
playwright.page.Page object (e.g. "click", "screenshot", "evaluate", etc).
It's also possible to pass callable objects that will be invoked as callbacks
and receive Playwright Page as argument.
method is the name of the method, *args and **kwargs
are passed when calling such method. The return value
will be stored in the PageMethod.result attribute.
If a PageMethod receives a callable object as its first argument, it will be
called with the page as its first argument. Any additional arguments are passed
to the callable after the page.
Certain Response attributes (e.g. url, ip_address) reflect the state after the last
action performed on a page. If you issue a PageMethod with an action that results in
a navigation (e.g. a click on a link), the Response.url attribute will point to the
new URL, which might be different from the request's URL.
Handling page events
A dictionary of Page event handlers can be specified in the playwright_page_event_handlersRequest.meta key.
Keys are the name of the event to be handled (e.g. dialog, download, etc).
Values can be either callables or strings (in which case a spider method with the name will be looked up).
See the upstream Page docs
for a list of the accepted events and the arguments passed to their handlers.
Notes about page event handlers
Event handlers will remain attached to the page and will be called for
subsequent downloads using the same page unless they are
removed later.
This is usually not a problem, since by default requests are performed in
single-use pages.
Event handlers will process Playwright objects, not Scrapy ones. For example,
for each Scrapy request/response there will be a matching Playwright
request/response, but not the other way: background requests/responses to get
images, scripts, stylesheets, etc are not seen by Scrapy.
Memory usage extension
The default Scrapy memory usage extension
(scrapy.extensions.memusage.MemoryUsage) does not include the memory used by
Playwright because the browser is launched as a separate process. The
scrapy-playwright package provides a replacement extension which also considers
the memory used by Playwright. This extension needs the
psutil package to work.
Update the EXTENSIONS
setting to disable the built-in Scrapy extension and replace it with the one
from the scrapy-playwright package:
Refer to the
upstream docs
for more information about supported settings.
Windows support
Just like the upstream Scrapy extension, this custom memory extension does not work
on Windows. This is because the stdlib resource
module is not available.
Examples
Click on a link, save the resulting page as PDF
class ClickAndSavePdfSpider(scrapy.Spider):
name = "pdf"
async def start(self):
yield scrapy.Request(
url="https://example.org",
meta=dict(
playwright=True,
playwright_page_methods={
"click": PageMethod("click", selector="a"),
"pdf": PageMethod("pdf", path="/tmp/file.pdf"),
},
),
)
def parse(self, response, **kwargs):
pdf_bytes = response.meta["playwright_page_methods"]["pdf"].result
with open("iana.pdf", "wb") as fp:
fp.write(pdf_bytes)
yield {"url": response.url} # response.url is "https://www.iana.org/domains/reserved"
Scroll down on an infinite scroll page, take a screenshot of the full page
class ScrollSpider(scrapy.Spider):
name = "scroll"
async def start(self):
yield scrapy.Request(
url="http://quotes.toscrape.com/scroll",
meta=dict(
playwright=True,
playwright_include_page=True,
playwright_page_methods=[
PageMethod("wait_for_selector", "div.quote"),
PageMethod("evaluate", "window.scrollBy(0, document.body.scrollHeight)"),
PageMethod("wait_for_selector", "div.quote:nth-child(11)"), # 10 per page
],
),
)
async def parse(self, response, **kwargs):
page = response.meta["playwright_page"]
await page.screenshot(path="quotes.png", full_page=True)
await page.close()
return {"quote_count": len(response.css("div.quote"))} # quotes from several pages
Specifying a proxy via the proxy Request meta key is not supported.
Refer to the Proxy support section for more information.
Unsopported signals
The headers_received and bytes_received signals are not fired by the
scrapy-playwright download handler.
Reporting issues
Before opening an issue please make sure the unexpected behavior can only be
observed by using this package and not with standalone Playwright. To do this,
translate your spider code to a reasonably close Playwright script: if the
issue also occurs this way, you should instead report it
upstream.
For instance:
When opening an issue please include a
Minimal, Reproducible Example
that shows the reported behavior. In addition, please make the code as self-contained as possible
so an active Scrapy project is not required and the spider can be executed directly from a file with
scrapy runspider.
This usually means including the relevant settings in the spider's
custom_settings
attribute:
Please make the effort to reduce the code to the minimum that still displays the issue.
It is very rare that a complete project (including middlewares, pipelines, item processing, etc)
is really needed to reproduce an issue. Reports that do not show an actual debugging attempt
will not be considered.
Logs and stats
Logs for spider jobs displaying the issue in detail are extremely useful
for understanding possible bugs. Include lines before and after the problem,
not just isolated tracebacks. Job stats displayed at the end of the job
are also important.
Deprecated features will be supported for at least six months
following the release that deprecated them. After that, they
may be removed at any time. See the changelog
for more information about deprecations and removals.
Works well with
Use together with scrapy-playwright: extensions, drivers, servers and companion tools.
playwrightPythie’s Index: 89A high-level API to automate web browsers141.5M downloads/mo
ScrapyPythie’s Index: 92A high-level Web Crawling and Web Scraping framework3.4M downloads/mo
camoufoxPythie’s Index: 88Wrapper around Playwright to help launch Camoufox1.2M downloads/mo
patchrightPythie’s Index: 85Undetected Python version of the Playwright testing and automation library.5.2M downloads/mo
playwright-stealthPythie’s Index: 46Make your playwright instance stealthy3.1M downloads/mo
rebrowser-playwrightPythie’s Index: 54A high-level API to automate web browsers102.4K downloads/mo