Download handlers
Download handlers are Scrapy components used to download requests and produce responses from them.
Using download handlers
The DOWNLOAD_HANDLERS_BASE and DOWNLOAD_HANDLERS settings
tell Scrapy which handler is responsible for a given URL scheme. Their values
are merged into a mapping from scheme names to handler classes. When Scrapy
initializes it creates instances of all configured download handlers (except
for lazy ones) and stores them in a similar
mapping. When Scrapy needs to download a request it extracts the scheme from
its URL, finds the handler for this scheme, passes the request to it and gets a
response from it. If there is no handler for the scheme, the request is not
downloaded and a NotSupported exception is raised.
The DOWNLOAD_HANDLERS_BASE setting contains the default mapping of
handlers. You can use the DOWNLOAD_HANDLERS setting to add handlers
for additional schemes and to replace or disable default ones:
DOWNLOAD_HANDLERS = {
# disable support for ftp:// requests
"ftp": None,
# replace the default one for http://
"http": "my.download_handlers.HttpHandler",
# http:// and https:// are different schemes,
# even though they may use the same handler
"https": "my.download_handlers.HttpHandler",
# support for any custom scheme can be added
"sftp": "my.download_handlers.SftpHandler",
}
See also
Unencrypted protocols and
Local and non-network resources, for the security implications of the
default http, ftp, file and data handlers.
Choosing a download handler per request
Added in version 2.20.0.
The DOWNLOAD_HANDLERS_BY_NAME setting registers handlers under a
name instead of a URL scheme. Such handlers are only used by requests that ask
for them through the download_handler metadata key:
DOWNLOAD_HANDLERS_BY_NAME = {
"playwright": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}
Request("https://example.com", meta={"download_handler": "playwright"})
download_handler also accepts a URL scheme, e.g. "https", to use
a handler from DOWNLOAD_HANDLERS on a request whose URL uses a
different scheme.
Requests keep their download_handler across redirects and retries,
and robots.txt requests inherit it from the request
that triggers them. To fetch robots.txt differently, use a downloader
middleware that acts on requests with the
is_robotstxt_request metadata key:
class DirectRobotsTxtMiddleware:
def process_request(self, request):
if request.meta.get("is_robotstxt_request"):
request.meta.pop("download_handler", None)
Replacing HTTP(S) download handlers
While Scrapy provides a default handler for http and https schemes,
users may want to use a different handler, provided by Scrapy or by some
3rd-party package. There are several considerations to keep in mind related to
this.
First of all, as http and https are separate schemes, they need
separate entries in the DOWNLOAD_HANDLERS setting, even though it’s
likely that the same handler class will be used for both schemes.
Additionally, some of the Scrapy settings, like DOWNLOAD_MAXSIZE,
are honored by the default HTTP(S) handler but not necessarily by alternative
ones. The same may apply to other Scrapy features, e.g. the
bytes_received and headers_received signals.
Lazy instantiation of download handlers
A download handler can be marked as “lazy” by setting its lazy class
attribute to True. Such handlers are only instantiated when they need to
download their first request. This may be useful when the instantiation is slow
or requires dependencies that are not always available, and the handler is not
needed on every spider run. For example, the built-in S3 handler is lazy.
Writing your own download handler
A download handler is a component that defines the following API:
- class scrapy.core.downloader.handlers.DownloadHandlerProtocol(*args, **kwargs)[source]
Interface that download handlers must implement.
Besides implementing this protocol, the contract of a download handler includes never calling
crawler.engine.download_async(), including indirectly by awaiting aRequestobject.
An optional base class for custom handlers is provided:
Exceptions raised by download handlers
Added in version 2.15.0.
The built-in download handlers raise Scrapy-specific exceptions instead of implementation-specific ones, so that code that handles these exceptions can be written in a generic way. We recommend custom download handlers to also use these exceptions.
- exception scrapy.exceptions.CannotResolveHostError[source]
Indicates that the provided hostname cannot be resolved.
- exception scrapy.exceptions.DownloadCancelledError[source]
Indicates that a request download was cancelled.
- exception scrapy.exceptions.DownloadConnectionRefusedError[source]
Indicates that a connection was refused by the server.
- exception scrapy.exceptions.DownloadFailedError[source]
Indicates that a request download has failed.
- exception scrapy.exceptions.DownloadTimeoutError[source]
Indicates that a request download has timed out.
Built-in HTTP download handlers reference
Scrapy ships several handlers for HTTP and HTTPS requests. While all of them support basic features, they may differ in support of specific Scrapy features and settings and HTTP protocol features. See the documentation of specific handlers and specific settings for more information. Additionally, as the underlying HTTP client implementations differ between handlers, the behavior of specific websites may be different when doing the same Scrapy requests but using different handlers.
Here is a comparison of some features of the built-in HTTP handlers, see the individual handler docs for more differences:
Handler |
Requirements |
HTTP |
Proxies |
Bad headers |
TLS |
IPv6 |
Header case |
|---|---|---|---|---|---|---|---|
asyncio |
1.1 |
HTTP |
Fail |
Stdlib |
Yes |
As written |
|
Reactor, twisted-http2 extra |
2 |
None |
Not applicable |
|
Needs a setting |
Lowercase |
|
Reactor |
1.1 |
HTTP |
Skip bad |
|
Needs a setting |
Capitalized |
|
asyncio, httpx extra |
1.1, 2 |
HTTP, SOCKS |
Fail |
Stdlib |
Yes, except through a proxy |
As written |
Bad header handling is what a handler does when a response has a bad header line, e.g. one with no colon in it, which some servers send. Handlers that skip bad header lines, like web browsers do, still parse the header lines that follow them; other handlers also lose those, or cannot download such responses at all.
Handlers that require a reactor resolve hosts, including proxy hosts and IPv6
address literals such as https://[::1]/, with the resolver set in
TWISTED_DNS_RESOLVER, whose default value only supports IPv4. To use
IPv6 with them, set it to scrapy.resolver.CachingHostnameResolver.
Because HTTP/2 requires lowercase header names, handlers only keep the case of your header names over HTTP/1.1.
You can find additional HTTP download handlers in the scrapy-download-handlers-incubator package. This package is made by the Scrapy developers and contains experimental handlers that may be included in some later Scrapy version but can already be used. Please refer to the documentation of this package for more information.
AiohttpDownloadHandler
Added in version 2.19.0.
Changed in version 2.20.0: In earlier versions, the handler was not lazy.
This handler supports http://host/path and https://host/path URLs and
uses the HTTP/1.1 protocol for them.
It’s implemented using the aiohttp library.
If you want to use this handler you need to replace the default ones for the
http and https schemes:
DOWNLOAD_HANDLERS = {
"http": "scrapy.core.downloader.handlers._aiohttp.AiohttpDownloadHandler",
"https": "scrapy.core.downloader.handlers._aiohttp.AiohttpDownloadHandler",
}
Features and limitations
Warning
This handler is experimental, and not yet recommended for production environments. Future Scrapy versions may introduce related changes without a deprecation period or warning or even remove it altogether.
HTTP proxies |
Yes |
SOCKS proxies |
No (not supported by the library) |
HTTP/2 |
No (not supported by the library) |
Bad header handling |
Fail (not supported by the library) |
|
DER bytes |
Per-request |
No (not supported by the library) |
Yes |
|
TLS implementation |
Standard library |
H2DownloadHandler
Note
Requires the twisted-http2 extra.
This handler supports https://host/path URLs and uses the HTTP/2 protocol
for them.
It’s implemented using twisted.web.client and the h2 library.
If you want to use this handler you need to replace the default one for the
https scheme:
DOWNLOAD_HANDLERS = {
"https": "scrapy.core.downloader.handlers.http2.H2DownloadHandler",
}
Features and limitations
HTTP proxies |
No (not implemented) |
SOCKS proxies |
No (not supported by the library) |
HTTP/2 |
Yes |
Bad header handling |
Not applicable (HTTP/2 only) |
|
|
Per-request |
Yes |
No (not implemented) |
|
TLS implementation |
|
Other limitations:
No support for HTTP/1.1.
IPv6 support requires setting
TWISTED_DNS_RESOLVERtoscrapy.resolver.CachingHostnameResolver.
Known limitations of the HTTP/2 support:
No support for HTTP/2 Cleartext (h2c), since no major browser supports HTTP/2 unencrypted (refer http2 faq).
No support for server pushes, which are ignored.
HTTP11DownloadHandler
http, https.This handler supports http://host/path and https://host/path URLs and
uses the HTTP/1.1 protocol for them.
It’s implemented using twisted.web.client.
Features and limitations
HTTP proxies |
Yes |
SOCKS proxies |
No (not supported by the library) |
HTTP/2 |
No (implemented as a separate handler) |
Bad header handling |
Skip bad, like web browsers do |
|
|
Per-request |
Yes |
Yes |
|
TLS implementation |
|
Changed in version 2.18.0: Bad header lines with no colon in them are now skipped, instead of making the whole response impossible to download.
Other limitations:
IPv6 support requires setting
TWISTED_DNS_RESOLVERtoscrapy.resolver.CachingHostnameResolver.A
Content-Lengthrequest header is sent in addition to the one built from the request body, and most servers reject requests with two.
HttpxDownloadHandler
Note
Requires the httpx extra.
Added in version 2.15.0.
This handler supports http://host/path and https://host/path URLs and
uses the HTTP/1.1 or HTTP/2 protocol for them.
It’s implemented using the httpx2 library.
If you want to use this handler you need to replace the default ones for the
http and https schemes:
DOWNLOAD_HANDLERS = {
"http": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
"https": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler",
}
Features and limitations
Warning
This handler is experimental, and not yet recommended for production environments. Future Scrapy versions may introduce related changes without a deprecation period or warning or even remove it altogether.
HTTP proxies |
Yes |
SOCKS proxies |
Yes (SOCKS5) |
HTTP/2 |
Yes |
Bad header handling |
Fail (not supported by the library) |
|
DER bytes |
Per-request |
No (not supported by the library) |
Yes |
|
TLS implementation |
Standard library |
Other limitations:
The handler creates a separate connection pool for each proxy URL (due to limitations of
httpx) which may lead to higher resource usage when using proxy rotation.Requests to a URL with an IPv6 address literal, such as
https://[::1]/, do not work through a proxy.
Unlike the Twisted-based handlers, this handler does not use the resolver
configured with TWISTED_DNS_RESOLVER, so it resolves IPv6 hosts
without needing that setting changed, and it is not affected by
DNS_TIMEOUT or by the DNSCACHE_ENABLED cache.
HTTPX_HTTP2_ENABLED
Added in version 2.17.0.
Default: False
Whether to enable HTTP/2 support in this handler.
Built-in non-HTTP download handlers reference
AioftpDownloadHandler
Added in version 2.20.0.
This handler supports ftp://host/path FTP URIs and ftps://host/path
FTPS URIs. FTPS uses implicit TLS on port 990 and explicit TLS on any
other port.
It’s implemented using the aioftp library.
A path ending in / is listed instead of downloaded. The response body is
the plain-text output of the FTP NLST command, one file or directory name
per line.
It supports SOCKS4 and SOCKS5 proxies if you install the
socks extra.
Warning
This handler is experimental, and not yet recommended for production environments. Future Scrapy versions may introduce related changes without a deprecation period or warning or even remove it altogether.
Limitations:
Only passive mode is supported: the handler cannot be used if
FTP_PASSIVE_MODEisFalse, and requests that set theftp_passiverequest meta key toFalseare downloaded in passive mode, with an error logged.
DataURIDownloadHandler
This handler supports RFC 2397 data:content/type;base64, data URIs.
FileDownloadHandler
This handler supports file:///path local file URIs. It doesn’t
support remote files.
FTPDownloadHandler
This handler supports ftp://host/path FTP URIs.
It’s implemented using twisted.protocols.ftp.
A path ending in / is listed instead of downloaded. The response
body is the plain-text output of the FTP NLST command, one file or
directory name per line.
S3DownloadHandler
Note
Requires the s3 extra.
This handler supports s3://bucket/path S3 URIs.
It’s implemented using the botocore library.