Release notes
Scrapy 2.20.0 (2026-11-06)
Highlights:
Web-browser-like detection of response encodings, base URLs and meta refresh redirects, powered by frostwork
Requests can be awaited to get their response
Non-asyncio Twisted reactors are deprecated
Security bug fixes
Scrapy now limits by default the memory that responses can take, fixing CVE-2017-14158.
In previous Scrapy versions, the only limit on the total size of responses in memory,
SCRAPER_SLOT_MAX_ACTIVE_SIZE, covered responses waiting for or going through spider callbacks. Responses to other requests, like those of media pipelines, had no limit. For example, when media pipelines downloaded files faster than they could store them, e.g. to Amazon S3, the downloaded files piled up in memory, so a crawled website could make Scrapy run out of memory.The new
RESPONSE_MAX_ACTIVE_SIZEsetting replacesSCRAPER_SLOT_MAX_ACTIVE_SIZEand covers all responses in memory, including those to awaited requests and to requests sent withExecutionEngine.download_async(). Use it to change or disable the limit. Theshelldisables it.HttpCompressionMiddlewarenow decodes at most 1 content coding per response by default, and drops responses that apply more withIgnoreRequest.In previous Scrapy versions, the number of content codings was unlimited, so a malicious server could send a response with a
Content-Encodingheader that chains thousands of codings (e.g.gzip, gzip, gzip, …) to make Scrapy run as many decompression passes, causing high CPU and memory usage. See the j72p-v7rm-cwm3 security advisory for details.To allow more content codings per response, set the new
COMPRESSION_MAX_ENCODINGSsetting.When
http_auth_domainis not set, the credentials fromhttp_userandhttp_passare now only sent to the origin (scheme, host and port) of the request where they were first used.In previous Scrapy versions, they were sent to any URL, so after a cross-origin redirect,
HttpAuthMiddlewareadded them again to theAuthorizationheader thatRedirectMiddlewarehad removed, sending them to the redirect target. A website could redirect Scrapy to a host under its control to steal those credentials. See the 466x-p45j-m4fx security advisory for details.(#8329)
When using a proxy from the
http_proxyorhttps_proxyenvironment variables, redirects now honor theno_proxyenvironment variable.In previous Scrapy versions, a redirect to a URL with the same scheme kept the proxy of the original request, even if the redirect host matched
no_proxy. A website could redirect Scrapy to an internal host, and that request would be sent through the proxy. Forhttp://URLs, this exposed the request to the proxy, including any cookies or credentials for that host, and allowed the proxy to forge the response. See the x3px-j3qh-fp5w security advisory for details.S3FilesStorenow uses HTTPS with the default Scrapy settings.In previous Scrapy versions, the default value of
AWS_USE_SSL,None, was incorrectly interpreted to mean “disable HTTPS”, soS3FilesStoreused plain HTTP when talking to S3 unless that setting was explicitly set toTrueorAWS_ENDPOINT_URLwas set to a custom HTTPS URL.An attacker who could observe that traffic could read the contents, S3 paths and metadata of the files uploaded by
FilesPipelineandImagesPipeline, the AWS access key ID (but not the secret access key) and, with temporary credentials, the session token (X-Amz-Security-Token). An attacker who could tamper with that traffic could make Scrapy falsely think that a file is up to date or was successfully stored. See the fwm7-29m4-rrj9 security advisory for details.To restore the previous behavior, set
AWS_USE_SSLtoFalse.LxmlLinkExtractorandSitemapSpidernow only followhttp://andhttps://URLs by default, plus URLs that use the scheme of the response they come from.In previous Scrapy versions, link extractors also followed
file://andftp://URLs, andSitemapSpiderfollowed URLs of any scheme. A crawled website could use that to make Scrapy read local files, send theFTP_USERandFTP_PASSWORDcredentials to an FTP server of its choosing, or send requests signed with theAWS_ACCESS_KEY_IDcredentials to an S3 bucket of its choosing. See the q7wc-mr9r-gcjh security advisory for details.To follow URLs with other schemes, use the new
schemesparameter ofLxmlLinkExtractoror the newsitemap_schemesattribute ofSitemapSpider.
Modified requirements
Dropped support for Python 3.10. (#8261)
New dependencies:
aiodns >= 3.3.0
aioftp >= 0.26.1
formerly >= 0.1.0
frostwork >= 0.2.2
typing-extensions >= 4.13.0 (on Python 3.12 and lower)
charset-normalizer is no longer a dependency. (#8393)
Increased the minimum versions of the following dependencies:
Changes to extras:
New
clipboard,memusageandsocksextras.gcs: google-cloud-storage 1.29.0 → 1.30.0httpx: httpx2 2.0.0 → 2.3.0images: Pillow 8.3.2 → 9.2.0s3: boto3 1.20.0 → 1.35.2, and aioboto3 >= 9.0.0 is now included.twisted-http2: Twisted 21.7.0 → 23.10.0uvloop: uvloop 0.16.0 → 0.17.0
(#6430, #7826, #7932, #8058, #8062, #8162, #8213, #8261, #8330, #8341, #8460)
Backward-incompatible changes
Changes to the
fetch()shortcut of the Scrapy shell:Requests are now downloaded with
ExecutionEngine.download_async()instead of being passed to the scheduler. As a result, spider middlewares and duplicate filtering are no longer applied to them.When a
Requestobject is passed, itscallbackanderrbackare no longer called, and a warning is issued if they are set.The engine is no longer started, so the
engine_startedandengine_stoppedsignals are not sent, and components that start on them, such as theMemoryUsageextension and the telnet console, do not run in the shell.
Changes to the behavior of
ExecutionEnginemethods that change its state:close_spider_async()now also stops the engine. Calling it while the spider is opening now closes the spider as soon as it is open, calling it while the spider is closing now completes immediately instead of waiting for the in-flight requests, and calling it after the spider has been closed no longer raisesRuntimeError.stop_async()now just callsclose_spider_async()with theshutdownreason. Calling it afteropen_spider_async()and beforestart_async()now closes the spider instead of raisingRuntimeError. Calling it while the spider is closing or after the engine has stopped now completes immediately, instead of raisingRuntimeErroror waiting for the in-flight requests.start_async()now raisesRuntimeErrorif called beforeopen_spider_async()has finished, instead of sending theengine_startedsignal anyway, and if called after the engine has stopped.The
engine_stoppedsignal is now sent only after allengine_startedhandlers have finished.If the spider is closed before the engine is started, for example by calling
close_spider_async()from aspider_openedhandler, theengine_startedandengine_stoppedsignals are not sent.Crawler.stop_async(), when called before the engine is running, e.g. while the spider is being opened, now closes the spider as soon as it is open, instead of being ignored.A
CloseSpiderexception raised while the spider is opening now closes the spider as soon as it is open, instead of being re-raised byopen_spider_async().crawl()anddownload_async()now raiseRuntimeErrorwhen called while the spider is closing, once the close has stopped waiting for the requests in progress.
Setting the
ExecutionEngine.runningattribute no longer has any effect, and is deprecated. Its value is nowFalsewhile the spider is closing. (#8181)FTPDownloadHandlernow enforcesDOWNLOAD_MAXSIZEandDOWNLOAD_WARNSIZE, also when usingftp_local_filename, so downloads bigger than 1 GiB now fail by default. To download bigger files, raise the limit to a size that fits them, withDOWNLOAD_MAXSIZEor with thedownload_maxsizerequest meta key for specific requests. You can also set the limit to0to lift it altogether. (#8213)The built-in HTTP download handlers now limit their open connections with the new
CONCURRENT_CONNECTIONS_PER_HANDLERsetting, whose default value is derived from the limit of open files of the process, or is 480 on Windows.HTTP11DownloadHandlerandH2DownloadHandlerhad no such limit before, andAiohttpDownloadHandlerandHttpxDownloadHandlerusedCONCURRENT_REQUESTSas their limit. If you setCONCURRENT_REQUESTShigher than that default, a warning is logged, and you need to setCONCURRENT_CONNECTIONS_PER_HANDLERor, on platforms other than Windows, raise the limit of open files of the process (see I get too many file descriptors in select() or Too many open files). (#2653, #5024, #5618, #7932)HttpxDownloadHandlerno longer falls back to thehttpxpackage when httpx2 is not installed. Install thehttpxextra to use it. (#7932)Responses that your code keeps in memory, e.g. in the
Request.metaof scheduled requests or in component attributes, now count towardRESPONSE_MAX_ACTIVE_SIZEuntil they are released, and so do responses in a reference cycle until Python’s garbage collector frees them. Keeping many responses can now slow down your crawl. To find out whether your crawl keeps responses alive, see Debugging memory leaks.If requests have been held back by the limit for 5 seconds with none being downloaded and no response released, Scrapy runs Python’s garbage collector and, if that releases no response, lets one request through, logging a warning the first time and increasing the new
response_max_active_size/bypass_countstat.Scrapy itself no longer keeps responses alive in reference cycles after a request fails, e.g. with an
HttpErrorthat no errback handles, or after a failed media pipeline download.Header names in
Headersobjects, i.e. inRequest.headersandResponse.headers, now keep the case they are first set with, instead of being converted toTitle-Case. Lookups are still case-insensitive, but code that iterates over header names and compares them toTitle-Casestrings must be updated.Over HTTP/1.1,
AiohttpDownloadHandlerandHttpxDownloadHandlernow send header names in the case you write them in, and keep the case of response header names as received. See the comparison of download handlers.get_retry_request(), and henceRetryMiddleware, now sets the newskip_dupefilter_oncerequest meta key on retry requests instead of setting theirdont_filterattribute toTrue. As a result, with schedulers that support that meta key, like the default one, requests derived from a retry request, e.g. redirects, are no longer exempt from duplicate filtering. (#6895, #8224)Requests whose meta is copied from a downloaded request, e.g. redirects and retries, are now assigned to the download slot of their own URL domain, instead of keeping the slot of the original request. Requests whose meta is copied from a request whose
download_slotrequest meta key you set keep that slot, so set it to keep redirects and retries in the slot of the original request. (#8337)http_userandhttp_passare now only sent to the origin (scheme, host and port) of the request that you set them on, so they are no longer sent after a cross-origin redirect. To send them to a different origin, set thehttp_auth_domainrequest meta key.HttpAuthMiddlewarealso no longer sets theAuthorizationheader of requests whose URL scheme is neitherhttpnorhttps. (#8329)Keys of component priority dictionaries, such as
DOWNLOADER_MIDDLEWARES, that cannot be resolved into a component, e.g. the import path of a component that no longer exists, now raiseValueError, even if their priority isNone. Some of them used to be silently ignored, and a missing module used to raiseModuleNotFoundErrorinstead. Fix the import path or remove the entry. (#7820, #8159)HttpCompressionMiddlewarenow raisesDecompressionErrorfor a response body that cannot be decompressed, instead of the exception of the underlying decompression library, e.g.zlib.error,OSErrororEOFError. Update any code that catches those exceptions, e.g. in request errbacks. (#8177)str()of aSpiderobject now returns itsname. Userepr()to get the previous output, e.g.<MySpider 'my_spider' at 0x7f0e2c1a3b50>. (#1576, #8086)The
scrapy.utils.defer.parallel()andscrapy.utils.defer.parallel_async()functions, now deprecated, return aDeferredthat fires withNone, instead of with the result list of aDeferredList. (#5182, #7959)The
process_response()method ofHttpCompressionMiddlewareis now a coroutine function. Code that calls it must now await it, and subclasses that override it and callsuper().process_response()must now beasync def. (#3751, #8153)The
item_scraped()method ofscrapy.extensions.feedexport.FeedExporter, and thestart_exporting()andfinish_exporting()methods ofscrapy.extensions.feedexport.FeedSlot, are now coroutine functions. (#5622, #6273, #7800)parent_idis now part ofRequest.attributes, soRequest.replace()andrequest_from_dict()pass aparent_idkeyword argument to the request class.Requestsubclasses whose__init__()method accepts neitherparent_idnor**kwargsmust be updated. (#8225)Item exporters now turn the values of fields without a serializer into lists if they are list-like, e.g. tuples or sets, and into dictionaries if they are items, recursively. This changes the output of
PickleItemExporter,MarshalItemExporter,PprintItemExporterand customBaseItemExportersubclasses, andCsvItemExporternow joins list-like values, e.g. sets, the way it joins lists. (#3888, #3890, #8057)The output of a request errback that runs because a download failed now goes through the
process_spider_output()methods of spider middlewares, withNoneas the response, and exceptions raised while iterating that output reach theirprocess_spider_exception()methods. Spider middlewares whose methods expect a response must now also handleNone. Built-in spider middlewares now also process that output, e.g.UrlLengthMiddlewarecan drop requests from such errbacks, andStartSpiderMiddlewarenow setsis_start_requestin itsprocess_start()method instead of inget_processed_request(). (#4999, #7992)Feed storages now refuse feed modes that they do not support, which prevents the crawl from starting. In particular, setting the
overwritefeed option toFalsefor an S3 feed, which used to log a warning, now raisesValueError. For a GCS feed, which used to log a warning and overwrite the file, it now appends to the file. (#5580, #7826, #8173)sitemap_follownow also filters the sitemap URLs declared inrobots.txtfiles. If you set it, make sure it matches the URLs of the sitemaps declared in therobots.txtfiles that you want to follow. (#1182, #8175)The
process_request()method ofHttpCacheMiddlewareis now a coroutine function. Code that calls it must now await it, and subclasses that override it and callsuper().process_request()must now beasync def. (#2744, #7915)XMLFeedSpider.parse_nodes()andCSVFeedSpider.parse_rows()are now asynchronous generators. Code that calls them must now iterate over their output withasync for. (#8392)The settings of the built-in storages of media pipelines are no longer set as class attributes of those storages, e.g.
S3FilesStore.POLICYkeeps its default value regardless ofFILES_STORE_S3_ACL. Read them from the storage object of the pipeline instead, e.g.pipeline.store.POLICY. (#7925)Scraper.slotand the deprecatedscrapy.core.scraper.Slotclass now take aCrawlerobject instead of a maximum active size, theirfinish_response()method no longer takes a result parameter, theirMIN_RESPONSE_SIZEattribute was removed, and their deprecatedactive_sizeattribute is read-only. (#6430)The engine status that the telnet console reports now includes
engine.response_active_sizeinstead ofengine.scraper.slot.active_sizeandengine.scraper.slot.needs_backout(). (#6430)The deprecated
METAREFRESH_IGNORE_TAGSsetting and the ignore_tags parameter of the deprecatedscrapy.utils.response.get_meta_refresh()function now raiseValueErrorfor tags other thanscript,noscriptandtemplate, and only whethernoscriptis listed has any effect.METAREFRESH_IGNORE_TAGSis ignored altogether ifMETAREFRESH_SCRIPTINGis set with the same or a higher priority. (#8393)Scrapy no longer calls the deprecated
spider_opened()andspider_closed()methods ofSpiderState, so overriding them in a subclass has no effect. Handle thespider_state_loadedandspider_state_savingsignals instead. (#5153, #7650, #7656)Due to the new minimum version of w3lib, 2.6.0:
Request URLs are now normalized the way web browsers normalize them, so
Request.urlandResponse.urlcan differ from the URL you pass, e.g.https://EXAMPLE.combecomeshttps://example.com/,https://example.com/a/../bbecomeshttps://example.com/b, andhttps://0x7f.1/becomeshttps://127.0.0.1/. Update any code that compares request or response URLs to literal strings.Request fingerprints might differ for some URLs, so that cached responses of
HttpCacheMiddlewareand the seen requests of a job directory from an earlier version might not match the same requests.
(#8393)
For encodings declared in the response,
TextResponse.encodingnow reports the Python codec names of the encodings that web browsers use, e.g.gbkinstead ofgb18030for agb2312label, andutf-16-leinstead ofutf-16. It also reportsutf-8instead ofcp1252when the response declares no encoding and its body is ASCII-only, e.g. empty. For encoding labels that web browsers decode as a single U+FFFD character, likehz, it reportsreplacement, which raisesUnicodeDecodeErrorwhen decoding any non-empty body, so useTextResponse.textinstead ofresponse.body.decode(response.encoding).TextResponse.textcan also differ:The detected encoding of responses that declare none and are not valid UTF-8 can change.
Encodings that web browsers ignore, like
utf-32orcp437, are now ignored when declared, and the encoding is detected instead. A<meta>tag or XML declaration that declares UTF-16 now means UTF-8.Encoding declarations in
<meta>tags are now found past the first 4096 bytes of the response body.Response bodies are decoded the way web browsers decode them, which for some encodings, like
euc-jp, differs from Python codecs.
(#8393)
The base URL of a response, used by
TextResponse.urljoin(), selectors and link extractors, and the meta refresh thatMetaRefreshMiddlewarefollows, are now found closer to the way web browsers find them. In particular, they are now found anywhere in the response body, instead of only in its first 4096 characters, the meta refresh with the shortest delay, and the last one among those with that delay, now wins over the first one, meta refreshes within<script>or<template>elements, or to the response URL itself, ignoring its fragment, are no longer followed, and the base URL is normalized like request URLs. (#8393)The
responseattribute ofSelectorobjects is now read-only. For the selector of a response, i.e.TextResponse.selector, it no longer keeps the response alive, and becomesNoneonce nothing else refers to the response. (#8245)A negative value of
FILES_EXPIRESorIMAGES_EXPIRESnow disables expiration, so that files are never downloaded again once fetched. Previously, it made files be downloaded again every time; set the setting to0for that. (#8046)Crawls closed because
start()raised an exception, or byCLOSESPIDER_ERRORCOUNT, now make thecrawlandrunspidercommands exit with code 1. (#8082, #8203)A blank line between contract lines in a callback docstring now starts a new batch of contracts, which needs its own
@urlline; otherwise, the contracts of that batch do not run.ContractsManager.extract_contracts()now returns a list of batches, each a list of contracts, andContractsManager.from_method()now returns a list of requests instead of a request orNone.
Deprecations
The following modules are deprecated, with no replacement:
scrapy.utils.benchserverscrapy.utils.consolescrapy.utils.datatypesscrapy.utils.displayscrapy.utils.ftpscrapy.utils.gzscrapy.utils.jobscrapy.utils.ossignalscrapy.utils.sitemapscrapy.utils.sslscrapy.utils.templatescrapy.utils.versions
The following functions, classes and methods are deprecated, with no replacement:
scrapy.core.scraper.Scraper.handle_spider_error()scrapy.spiders.sitemap.iterloc()scrapy.utils.defer.aiter_errback()scrapy.utils.defer.iter_errback()scrapy.utils.defer.parallel()scrapy.utils.defer.parallel_async()scrapy.utils.python.MutableAsyncChain
scrapy.utils.python.garbage_collect()is deprecated, usegc.collect()instead. (#8367)Passing a coroutine to
scrapy.utils.spider.iterate_spider_output(), for which it returns aDeferredinstead of an iterable, is deprecated. Await the coroutine and pass its result instead. (#8394)Passing a synchronous iterable to
scrapy.core.scraper.Scraper.handle_spider_output_async()is deprecated, pass an asynchronous iterable instead. (#8288)scrapy.utils.reactor.is_asyncio_reactor_installed()is deprecated. To check for asyncio support, useis_asyncio_available(). To check whether a reactor is installed, usescrapy.utils.reactor.is_reactor_installed(). See Supporting older Scrapy versions for code that must also support older Scrapy versions. (#8128, #8454)Defining a
parse_item()method in aXMLFeedSpidersubclass is deprecated. Defineparse_node()instead. (#8147)Exceptions that the
process_response()method of a downloader middleware raises can now reach theprocess_exception()methods of the downloader middlewares that have not processed the response yet, so thatRetryMiddlewarecan retry them. Because existingprocess_exception()methods may not expect those exceptions, e.g. theIgnoreRequestraised to drop a response, this only happens when the newDOWNLOADER_MIDDLEWARE_RESPONSE_EXCEPTIONSsetting isTrue. Its default value,False, is deprecated, and a warning is issued when an exception would reach theprocess_exception()method of a non-Scrapy downloader middleware if the setting wereTrue. Check that those methods handle such exceptions as intended, and set the setting toTrue. New projects generated withstartprojectalready do. (#7790, #8177)scrapy.utils.deprecate.create_deprecated_class()is deprecated, useformerly.deprecated_class()from formerly instead.scrapy.utils.decorators.deprecated()is deprecated, usewarnings.deprecated()instead (ortyping_extensions.deprecated()on Python 3.12 and lower). (#7894)scrapy.utils.url.add_http_if_no_scheme()is deprecated. Usew3lib.url.add_http_if_no_scheme()instead. (#2186, #8189)The following methods of
Headersare deprecated:fromkeys(): pass(key, value)pairs toHeadersinstead.has_key(): use theinoperator instead.normkey()andnormvalue().setlist(): assign the list instead, e.g.headers[key] = values.setlistdefault(): usesetdefault()instead.to_unicode_dict(): useto_tuple_list()instead.
The
spider_closed_callbackparameter ofExecutionEngineis deprecated. Closing the spider now stops the engine, andCrawler.crawl_async()completes when that happens. (#6916, #8217)Setting the
ExecutionEngine.runningattribute is deprecated, and has no effect. (#8181)Custom schedulers that do not set
supports_skip_dupefilter_oncetoTrueare deprecated, including subclasses of the default scheduler that override itsenqueue_request()method. Scrapy turnsskip_dupefilter_onceintodont_filter=Truefor them, with a warning. To update a scheduler, handleskip_dupefilter_oncein itsenqueue_request()method and setsupports_skip_dupefilter_oncetoTrue. (#6895, #8224)The
overwritefeed option is deprecated. Use the newmodefeed option instead:"overwrite"instead ofTrue,"append"instead ofFalse. Theoverwriteattribute ofFTPFeedStorageis deprecated as well.The default value of the new
FEED_MODEsetting,None, is also deprecated: it will change to"create"in a future version of Scrapy, so that existing feed targets are not modified. SetFEED_MODE, or themodeoption of every feed, to silence the deprecation warning. New projects setFEED_MODEto"create"in theirsettings.pyfile. (#5580, #7826)The
STORE_SCHEMESattribute ofFilesPipelineis deprecated. Use the newMEDIA_STORAGESsetting instead. (#5991, #7925)The
spider_opened()andspider_closed()methods ofSpiderStateare deprecated. Use the newspider_state_loadedandspider_state_savingsignals instead. (#5153, #7650, #7656)The spider and to_native_str_type parameters of
scrapy.robotstxt.decode_robotstxt()are deprecated and have no effect. (#8316)Calling
AsyncCrawlerRunner.crawl()without a running asyncio event loop whileTWISTED_REACTOR_ENABLEDisFalseis deprecated. Call it from a coroutine that runs in the event loop instead, e.g. one passed toasyncio.run(). (#7201, #7681, #8327)ImagesPipeline.convert_image()has a new image_format keyword-only parameter with the original image format. Overriding the method without that parameter, and calling it without it, are deprecated. (#8198, #8457)The
SCRAPER_SLOT_MAX_ACTIVE_SIZEsetting is deprecated. UseRESPONSE_MAX_ACTIVE_SIZEinstead.scrapy.core.scraper.Slotis deprecated as well, and so are theactive_sizeandmax_active_sizeattributes and theneeds_backout()method ofScraper.slot. UseExecutionEngine.response_active_size,RESPONSE_MAX_ACTIVE_SIZEandExecutionEngine.needs_backout()instead.(#6430)
Using a Twisted reactor other than
AsyncioSelectorReactoris deprecated, be it set through theTWISTED_REACTORsetting, installed by code outside Scrapy, or passed toinstall_reactor(). SettingTWISTED_REACTORtoNoneor""is deprecated as well. Remove any customTWISTED_REACTORsetting from your code.The
FORCE_CRAWLER_PROCESSsetting is deprecated as well.Passing an encoding that web browsers do not support, e.g.
cp437, to the encoding parameter ofTextResponseis deprecated. To decode a response body with such an encoding, useresponse.body.decode(encoding). (#8393)scrapy.utils.response.get_base_url()andscrapy.utils.response.get_meta_refresh()are deprecated. Use the newTextResponse.base_urlandTextResponse.meta_refreshattributes instead. When there is no meta refresh, the latter isNoneinstead of(None, None). (#8393)The
METAREFRESH_IGNORE_TAGSsetting is deprecated. Use the newMETAREFRESH_SCRIPTINGsetting instead. (#8393)
New features
Requestobjects can now be awaited, e.g. in a spider callback, to send them and get their response. See Inline requests. (#1144, #8207)Added a
DOWNLOAD_HANDLERS_BY_NAMEsetting and adownload_handlerrequest meta key, to choose a download handler per request, e.g. a browser-based handler for only some requests. The default request fingerprinter takesdownload_handlerinto account when it does not match the URL scheme.RobotsTxtMiddlewarenow copiesdownload_handlerfrom the request that triggers arobots.txtrequest, and sets the newis_robotstxt_requestrequest meta key on therobots.txtrequests that it sends.Added a
body_filerequest meta key, which writes the response body into a file as it is downloaded, so that large responses can be downloaded without keeping them in memory, with download handlers that support it. Set it to a file path, or toTrueto write into a new temporary file. Those requests get aBodyFileResponse, and neither they nor their responses count towardRESPONSE_MAX_ACTIVE_SIZE. (#3880, #4620, #5044, #7987, #8466)Sending a shutdown signal, e.g. with Ctrl+C, a second time now triggers a fast stop, which drops queued and in-progress downloads instead of waiting for them to finish. Sending it a third time forces an unclean shutdown, which used to happen on the second signal. Dropped requests are counted in the new
downloader/request_dropped_countstat.Crawler.stop_async(),CrawlerRunner.stop()andAsyncCrawlerRunner.stop()have a new keyword-onlymodeparameter that can be"graceful"(the default),"fast"or"force", which works as"fast"unless you useCrawlerProcessorAsyncCrawlerProcess.stop_async()andclose_spider_async()accept"graceful"and"fast". A customDOWNLOADERclass needs astop()coroutine method, returning the number of dropped requests, for fast stops to drop its downloads. (#4749, #5000, #7455, #8296, #8312)Added the
delayrequest meta key, which holds a request for at least the given number of seconds before sending it, and thedelayedrequest meta key, which lists the delays that a request has been held for. (#802, #3835, #4980, #5015, #7873)Added
TextResponse.base_urlandTextResponse.meta_refresh, which return the base URL of a response and theMetaRefreshthat a web browser with JavaScript enabled would follow, and which you can set to override what the response body says. WhenMETAREFRESH_SCRIPTINGisFalse,MetaRefreshMiddlewareignores an overriddenmeta_refresh. (#8393)Added a
METAREFRESH_SCRIPTINGsetting, which you can set toFalseto follow the meta refresh that a web browser with JavaScript disabled would follow. (#8393)Added a
FEED_MODEsetting and amodefeed option, which set what happens when the target of a feed already exists:"append"to it,"overwrite"it, or"create", which leaves it untouched, logs an error and increases thefeedexport/conflicts/<storage class>stat. Custom feed storages declare the modes that they support with the newsupported_modesattribute.The
-ocommand-line option also followsFEED_MODE, so in a project withFEED_MODEset to"create",-oleaves an existing file untouched. Use-Oto overwrite it. (#5580, #7826)Added
DiskDupeFilter, aDUPEFILTER_CLASSthat keeps request fingerprints in an SQLite database on disk instead of in memory, to lower memory usage on large crawls. (#5307, #7952)Added a
JOBDIR_SYNC_EVERYsetting to write theactive.jsonfile of the job directory, and the database ofDiskDupeFilter, while the crawl runs, so that a crawl killed before it can stop cleanly can resume from its latest state, provided thatSCHEDULER_DISK_QUEUEandSCHEDULER_START_DISK_QUEUEuse SQLite-based queues. CustomSCHEDULER_PRIORITY_QUEUEclasses need the newchangedattribute andstate()method to support it.active.jsonis also now written atomically, so that it cannot be left half-written.Added
Request.id, a unique identifier of each request, andRequest.parent_id, theidof the request it derives from, which Scrapy sets for requests from callbacks and errbacks, fromResponse.follow()and fromRequest.replace(), e.g. redirects and retries. Use the new parent_id parameter ofRequestto set it on requests that your code builds on behalf of another request, e.g. in a downloader middleware. Both survive serialization, e.g. into the disk queues of a job directory. (#8225)Added a
genrequestcommand, which prints the Python code of aRequestobject equivalent to a cURL command, given as an argument or read from the system clipboard with the newclipboardextra. (#3990, #3991, #8058)Added a
completecommand, which prints a shell completion script for Bash, fish or Zsh. Completion covers the spiders, settings and templates of the current project, and custom commands, which can provide their own candidates by overriding the newcomplete_argument()andcomplete_option()methods. It replaces the completion scripts that were in theextrasdirectory of the source code repository. (#6453, #7899)Added a
STICKY_META_KEYSsetting to copy request metadata keys from a response into the follow-up requests yielded by its callback, handled by the newStickyMetaParamsMiddleware.The new middleware has priority 1000 in
SPIDER_MIDDLEWARES_BASE, andMetaCopyDetectionMiddlewaremoved from 1000 to 999.Rulehas newnameandfrom_rulesparameters, to apply a rule only to responses reached through specific other rules. (#982, #8066)A callback docstring can now define several batches of contracts, one per paragraph, and a batch can repeat
@urlto check the callback against more than one sample request. Custom contracts can set the newgenerates_requestattribute ofContracttoTrueto behave like@url. (#768, #8043)The Google Cloud Storage feed storage now supports the
"append"feed mode, instead of logging a warning and overwriting the feed. (#7823, #8173)FILES_EXPIRESandIMAGES_EXPIRESnow support fractional numbers of days, e.g.0.5for 12 hours, and negative values, which disable expiration, so that files are never downloaded again once fetched. (#2309, #4731, #8046)The reactor_path parameter of
install_reactor()is now optional, and defaults to the asyncio reactor. (#8125)Added a
DOWNLOADER_MIDDLEWARE_RESPONSE_EXCEPTIONSsetting which, whenTrue, passes exceptions raised by theprocess_response()method of a downloader middleware to theprocess_exception()methods of the downloader middlewares that have not processed the response yet. This allowsRetryMiddlewareto retry responses that other middlewares reject, e.g. responses that cannot be decompressed, for whichDecompressionErroris now part ofRETRY_EXCEPTIONS. (#1900, #3506, #7790, #8177)CloseSpidercan now be raised from downloader middlewares to close the spider. (#2578, #8177)Added
JsonValidationMiddleware, with priority 560 inDOWNLOADER_MIDDLEWARES_BASEand enabled with theJSONVALIDATION_ENABLEDsetting, which raisesjson.JSONDecodeErrorfor successfulJsonResponseresponses with an invalid JSON body.json.JSONDecodeErroris now part ofRETRY_EXCEPTIONS, so those responses are retried ifDOWNLOADER_MIDDLEWARE_RESPONSE_EXCEPTIONSisTrue. (#8215)Added an error keyword-only parameter to
CloseSpiderandclose_spider_async(), to mark a crawl as failed. Failed crawls set the newfinish_reason_errorstat toTrue, geterror=Truein theirspider_closedsignal, and make thecrawlandrunspidercommands exit with code 1. Crawls closed becausestart()raised an exception (start_error) are now also marked as failed, and so are crawls closed byCLOSESPIDER_ERRORCOUNT. (#1241, #2171, #3653, #3654, #8082, #8203, #8204, #8352, #8357)Added an
IMAGES_PRESERVE_FORMATsetting to keep images in their original format instead of converting them to JPEG. Stored images then get no file extension. (#1705, #2471, #8198)Added an
item_processorfeed option to replace each item with any number of items in a given feed, and afeedexport/item_count/<storage class>stat with the number of exported entries per storage class. (#5905, #7911)Added an
UPLOAD_TIMEOUTsetting to set how long uploads to remote feed storages and media pipeline storages (Amazon S3, Google Cloud Storage and FTP) wait for a response before giving up. (#5011, #8162)Added a
MEDIA_CACHE_SIZEsetting to limit how many download outcomes media pipelines keep in memory, which by default they keep for the whole crawl. (#939, #8193)LOG_FORMATnow supports a%(spider)splaceholder with the name of the spider that triggered the log message, or-for messages not tied to a spider. (#1576, #8086)StatsCollectorobjects are nowmutable mappingsof stats, e.g.stats["hostname"] = socket.gethostname(). (#3230, #8241)The
start_exporting(),export_item()andfinish_exporting()methods of item exporters used by feed exports, and theopen()andstore()methods of feed storages, can now be coroutine functions. (#5622, #6273, #7800)Added a
LOG_LEVELSsetting, to set the minimum log level of specific loggers, overriding the levels that Scrapy sets by default. (#2231, #7921)The
settingscommand now takes the settings of enabled add-ons into account, and has a new--spideroption to take the settings of a spider into account as well. (#7010, #7828)Added a
skip_dupefilter_oncerequest meta key, which skips duplicate filtering for a request without affecting the requests derived from it, and asupports_skip_dupefilter_onceattribute for schedulers to declare that they support it. (#6895, #8224)The FTP download handlers now list the contents of a directory when the URL path is empty or ends in
/, returning the output of the FTPNLSTcommand, one name per line. (#1478, #2505, #8197)The memory usage extension now works on Windows, with the new
memusageextra. (#4070, #8062)Added
EngineStateandExecutionEngine.state, which tell the lifecycle state of the engine. (#6916, #8217)The
fetch,view,shellandparsecommands now support a--curloption, to build the request from a cURL command instead of from a URL argument. (#36, #447, #7703)Added an experimental FTP and FTPS download handler,
AioftpDownloadHandler, used by default when running without a Twisted reactor. The newsocksextra enables its support for SOCKS proxies. (#7261, #8213, #8341)Added
MEDIA_STORAGESandMEDIA_STORAGES_BASEsettings, which map URL schemes to the storage classes of the media pipelines, to support additional schemes or replace built-in storages. Storage classes can define afrom_crawler()class method to read settings, including settings specific to the files or images pipeline, or to a pipeline subclass.Pipelines no longer share the settings of built-in storages, so that e.g. the files and images pipelines of a crawl can use different values for
FILES_STORE_S3_ACLandIMAGES_STORE_S3_ACL. (#5991, #7925)Added
FILES_CHECKSUM_ALGORITHMandIMAGES_CHECKSUM_ALGORITHMsettings, to calculate the checksums of media pipeline files with ahashlibalgorithm other than MD5. (#3306, #7951)LxmlLinkExtractorhas a newschemesparameter to choose the URL schemes of extracted links, andscrapy.linkextractors.SUPPORTED_SCHEMESlists the URL schemes that Scrapy can download out of the box. (#4979, #7994)Added
SitemapSpider.sitemap_request(), which you can override to customize the requests thatSitemapSpiderbuilds from sitemap entries, e.g. to pass sitemap data to callbacks. (#2565, #3543, #8175)Added a
sitemaps()method toRobotParser, implemented by the Protego and Robotexclusionrulesparser parsers, which returns the sitemap URLs declared in therobots.txtfile, and a response parameter to therobots_parsedsignal. (#3967, #8069, #8175)Added the
spider_state_loaded,spider_state_savingandfeed_slots_initializedsignals. (#5153, #7650, #7656)Added an event loop lag monitor extension, enabled by default, which logs a warning when code blocks the event loop for longer than the new
EVENT_LOOP_LAG_THRESHOLDsetting, 10 seconds by default. (#3197, #8093)When
RobotsTxtMiddlewaredenies at least one start request and no start request can be crawled, the crawl now finishes with therobotstxt_deniedfinish_reasoninstead offinished, and an error is logged. (#6164)urlparse_cached()now also accepts a URL string, andscrapy.utils.url.url_is_from_any_domain(),url_is_from_spider()andurl_has_any_extension()now also acceptRequestandResponseobjects. Built-in components now reuse URL parsing results more, which makes crawls faster. (#8247)Added a
proxy_headersrequest meta key, to send headers to the proxy set inproxy, e.g. in theCONNECTrequest of HTTPS URLs. (#3329, #7888)Added
UriUserInfoMiddleware, enabled by default, which removes the credentials from request URLs likehttps://user:pass@example.comand sets them ashttp_userandhttp_pass, or asftp_userandftp_passwordfor FTP URLs. As a result,Request.urlandResponse.urlno longer include those credentials after that middleware. (#669, #851, #1466, #4474)Added an
HTTPCACHE_SCOPEsetting, which allows sharing the HTTP cache across spiders and, withFilesystemCacheStorage, splitting it by request host instead of by spider. (#5166, #5175, #7964)Added a
LOG_ROOT_FORMATTERsetting, which sets the formatter of the root log handler. Such formatters implement the newLogRootFormatterProtocol, and the newLogRootFormatteris the default one, which you can also use in your own log handlers.LOG_COLORalso works with custom formatters. (#8336)Added a
CONNECTION_KEEPALIVE_TIMEOUTsetting, which sets how long the built-in HTTP download handlers keep idle connections open for reuse. Its default value, 240 seconds, is the timeout that the Twisted-based handlers already used; the aiohttp- and httpx-based handlers used their library defaults, 15 and 5 seconds respectively. (#8342)Added
Response.follow_redirect(), which returns a request that follows theLocationheader of the response. (#8331)When
DOWNLOAD_FAIL_ON_DATALOSSor thedownload_fail_on_datalossrequest meta key isFalse, hitting the download timeout while receiving the response body now returns the part of the response received so far, with thedatalossflag, instead of raisingDownloadTimeoutError, with all built-in download handlers exceptFTPDownloadHandler. (#3407, #3492, #8084, #8464)HTTP11DownloadHandlernow supports proxies with an IPv6 address, proxies whose host name only resolves to IPv6 addresses, given an IPv6-capableTWISTED_DNS_RESOLVER, and HTTPS requests to IPv6 addresses through a proxy. (#6674, #7090, #8116, #8343)When asyncio support is available and
aioboto3is installed, S3 feed storage uploads files with it, instead of runningboto3in a thread. Similarly, the S3 storage of media pipelines usesaiobotocore, when installed, instead ofbotocore. (#3845, #8330, #8339)Added a
CONCURRENT_CONNECTIONS_PER_HANDLERsetting, which limits the number of connections, idle ones included, that each download handler keeps open. By default, the limit is derived from the maximum number of open files allowed for the process, or from theselect.select()limit on Windows, to preventToo many open fileserrors (see I get too many file descriptors in select() or Too many open files). (#2653, #5024, #5618, #7932)Added a
REDIRECT_HTTP_CODESsetting and aredirect_http_codesrequest meta key, which set the response status codes whoseLocationheaderRedirectMiddlewarefollows, e.g. to follow theLocationheader of 201 responses. Media pipelines withMEDIA_ALLOW_REDIRECTSenabled leave responses with those status codes toRedirectMiddleware. (#1615, #7801)HTTP11DownloadHandlernow supportshttps://proxy URLs forhttps://destination URLs. (#5828, #7776)When several requests for the same resource are sent concurrently,
HttpCacheMiddlewarenow downloads it only once, and, if the response is cached, serves it from the cache to the other requests. The newhttpcache/waitstat counts the requests that waited for another one. (#2744, #7915)XMLFeedSpider.parse_node(),CSVFeedSpider.parse_row()and the errback ofRulecan now be defined as coroutine functions (async def) or asynchronous generator functions. (#8392)item_completed()in subclasses ofMediaPipelinecan now be defined as a coroutine function (async def), andstat_file()in custom media storages can now awaitasynciocode. (#8413)BaseSettings.getlist()now parses a string that is a JSON list, e.g.-s 'MY_LIST=["a,b", "c"]', so that items that contain commas can be set from the command line. (#8416)Added a
RESPONSE_ROUGH_SIZEsetting, theExecutionEngine.response_active_sizeattribute, and therequest_backout_seconds/concurrency,request_backout_seconds/response_max_active_sizeandrequest_backout_seconds/totalstats. See Identifying crawl bottlenecks. (#5302, #6206, #6430)
Improvements
The encoding of a response that doesn’t declare one is now detected the way web browsers do: UTF-8 if the body is valid UTF-8, otherwise a guess based on the body and on the top-level domain of the response URL, as Firefox does. Encoding declarations in
<meta>tags are also found the way web browsers find them, and declared encoding names are mapped to encodings the way web browsers map them, e.g.gb2312to GBK instead of GB18030. (#8393)With parsel 1.12.0+,
Selectorobjects created from a UTF-8 response now parse the response body as is, instead of decoding it first, which saves time and memory. (#5906, #8195, #8222, #8393)Responses are now freed as soon as nothing refers to them, also after using their selector or after their callback raises an exception, instead of when the garbage collector runs, which lowers peak memory usage. (#2977, #8245)
The reactor settings
DNSCACHE_ENABLED,DNSCACHE_SIZE,DNS_TIMEOUT,REACTOR_THREADPOOL_MAXSIZEandTWISTED_DNS_RESOLVERcan now be set from a spider when usingCrawlerProcessorAsyncCrawlerProcess. When running multiple spiders in the same process, the values of the first spider are used, and a warning is issued for any later spider that defines a different value. The DNS resolver now gets theCrawlerof that first spider in itsfrom_crawler()method. (#5988, #7923)The
runspidercommand now accepts file paths without an extension, such as the ones of Bash process substitution (scrapy runspider <(…)). (#4827, #8036)Items are now processed by tasks started on demand, instead of by a fixed number of tasks, one per
CONCURRENT_ITEMS, started for every response, so a highCONCURRENT_ITEMSvalue no longer slows down crawls.CONCURRENT_ITEMSvalues lower than1now work as1. (#5182, #7959)Exceptions raised while exporting an item to a feed now include the item in a note. (#2775, #8191)
When a
TextResponseis created with astrbody and a UTF-8 encoding, that body is now reused astextinstead of being decoded again. (#8220)Improved the performance of link extraction with
LxmlLinkExtractor. (#8126)Compressed response bodies of 8 KiB or more are now decompressed in a thread, so that other responses can be processed meanwhile. (#3751, #8153)
The Scrapy version and the versions of
LOG_VERSIONSare now logged when each crawler is set up, after add-ons and spider settings are applied, so that they can changeBOT_NAMEandLOG_VERSIONS. They are now also logged when usingCrawlerRunnerorAsyncCrawlerRunner. Add-ons can now log the versions of their dependencies. (#8246)scrapy.pipelines.files.S3FilesStorenow supports any header that botocore supports for uploads, and media pipelines now document how to set custom headers for files uploaded to Amazon S3. (#4788, #4813, #8171)H2DownloadHandlernow sends theContent-Lengthrequest header that you set, instead of replacing it, with a warning, with one built from the request body. (#4919, #7944)H2DownloadHandlernow supportsDOWNLOAD_FAIL_ON_DATALOSSand thedownload_fail_on_datalossrequest meta key: when the setting or meta key isFalse, responses cut short by a lost connection are now returned with thedatalossflag; otherwise, they now fail withResponseDataLossErrorinstead ofDownloadFailedError. HTTP/2 data loss is now also detected byHttpxDownloadHandler. (#5048, #7989)Spiders that request the
robots.txtfile of a host, likeSitemapSpider, no longer download it twice whenROBOTSTXT_OBEYisTrue:RobotsTxtMiddlewarenow parses the response of a request for therobots.txtfile of a host, if it has not downloaded it yet, instead of downloading it again. (#3967, #8069)Requests that set the
download_maxsizerequest meta key but notdownload_warnsizeno longer log a warning based onDOWNLOAD_WARNSIZE. (#8213)AiohttpDownloadHandleris now lazy. (#8346)Connecting a handler to a built-in signal, where the handler declares an argument which the signal never sends, e.g. because of a typo, now issues a warning. (#8345)
call_later()and the processing of the output of spider callbacks now run in thecontextvarscontext that was current when they were scheduled also when not using the asyncio reactor, so that context variables set by your code, e.g. for tracing or logging, are kept. (#8347)Improved the performance of
scrapy.utils.python.binary_is_text(), which is used to pick the class of responses. (#8362)CookiesMiddlewarenow ignores received cookies with a__Secure-or__Host-name prefix that do not meet the requirements of that prefix, as web browsers do, e.g. such cookies received over plain HTTP. (#5431, #8431)Improved the performance of feed exports, especially for items with scalar field values. (#8461)
Improved the performance of
StatsCollectormethod calls. (#8243)Other code refactoring and improvements. (#8262, #8263, #8295, #8313, #8323, #8335, #8353, #8365, #8385, #8391, #8415)
Bug fixes
FTPDownloadHandlernow raisesDownloadFailedErrorwhen the server drops the connection, so that those downloads are retried. (#1511, #8206)FilesPipelinenow treats responses with the 201 status code as successful downloads. (#8349)The
Cookieheader now lists cookies with the same path length from oldest to newest, as RFC 6265 Section 5.4 requires. (#5431, #8321)The
runspidercommand now runs the given file even if its name matches that of an already imported module, e.g.json.py. (#8036, #8463)The
checkcommand now reports errors that prevent a spider from crawling, e.g. errors raised while creating the spider, instead of silently ignoring them. (#3716, #7991)Request.from_curl()now handles headers without a value (-H 'Name;') as curl does, ignores headers that curl would not send, supports-uwith a user name and no password, and raisesValueErrorfor an empty command, instead of failing with unexpected exceptions. It also turns-H 'Name:'into a header set toNone, i.e. not sent, instead of a header with an empty value, accepts Bash$'…'quoting in any argument, e.g. headers, although it does not decode backslash escapes, and keeps a leading$in request data instead of removing it.Request.to_curl()now includes every value of repeated headers, handles headers set toNoneand no longer fails on headers that are not valid UTF-8.Headers.to_tuple_list()no longer raisesUnicodeDecodeError; bytes that cannot be decoded are replaced with U+FFFD. (#2592, #2637, #8192)copy.copy()on anItemnow returns a shallow copy, likeItem.copy(). It used to return an item that shared its fields with the original, so that setting or deleting a field on one also did it on the other. (#8172)Calling
exit()orquit()in the telnet console now closes the connection, instead of logging an unhandled error. (#3853, #8065)An exception raised while building the
SCHEDULERis now reported as is, instead of being followed by aRuntimeErrorabout an unassigned engine slot. (#8169)The
lastseenfield of the representation of a downloader slot, e.g. in the telnet console, now shows the monotonic timestamp of the last activity instead of a meaningless date. (#8182)SitemapSpidernow resolves relative and protocol-relative URLs in sitemaps against the sitemap URL. (#965, #8210)CrawlSpidernow follows the links of a response also when the callback of the matching rule raises an exception. (#4108, #8200)A feed URI with a placeholder that is neither a spider attribute nor returned by the
uri_paramsfunction now makes only that feed be skipped, with an error logged, instead of raisingKeyErrorand leaving the remaining feeds unopened. (#2089, #8205)Fixed the file modification times that
FilesPipelinereads from Amazon S3, Google Cloud Storage and FTP storages to applyFILES_EXPIRES. S3 and Google Cloud Storage times were off by the UTC offset of the local time zone, and FTP times were misread. (#8186, #8196)Lines of a callback docstring that start with
@but do not name a registered contract, e.g. a decorator in a code example, are now ignored, instead of raisingKeyErroror making thecheckcommand treat the callback as having contracts. As a result, a misspelled contract name is also ignored. (#8226)The
benchcommand now listens on a random free port, instead of failing when port 8998 is in use. (#8230)CONCURRENT_REQUESTS_PER_DOMAINand theconcurrencykey ofDOWNLOAD_SLOTSare now enforced when using asyncio with no download delay. (#8256, #8257)SitemapSpidernow detects XML sitemaps also in responses that are notXmlResponseobjects, e.g. from third-party download handlers, based on their headers, URL and body. (#6362, #7904)Fixed the handling of headers that are not valid UTF-8 or ASCII in some download handlers:
HttpxDownloadHandlerno longer fails on non-ASCII request headers.AiohttpDownloadHandlerno longer fails on request or response headers that are not valid UTF-8. Invalid UTF-8 in request headers is sent as U+FFFD, with a warning.H2DownloadHandlerno longer fails, or hangs, on request or response headers that are not valid UTF-8.
(#8265)
Headers.get()now returns the given default value for a header set toNone. (#8268)Fixed the
downloader/request_bytesanddownloader/response_bytesstats, which miscounted line breaks for requests with all headers set toNoneand for responses with multi-value headers, andscrapy.utils.request.request_httprepr(), which added an extra line break for requests with all headers set toNone. (#8266, #8271)Changing the header values in the output of
Request.to_dict()orResponse.to_dict()no longer changes the original request or response. (#8269)HTTP11DownloadHandlernow closes the proxy connection of an HTTPS request that times out, or is otherwise cancelled, before the proxy has established the tunnel. (#3614, #7810)RedirectMiddlewareno longer copies the fragment of the original URL into the redirect URL when theLocationheader ends with an empty fragment (#). (#8100)When using a job directory, the default scheduler now pops requests by
priorityacross its memory and disk queues, instead of popping every request from the memory queue before any from the disk queue.Custom
SCHEDULER_PRIORITY_QUEUEclasses need to implement the newnext_priority()method to get this behavior.PriorityQueueProtocoldocuments the interface of priority queue classes. (#3666, #8237)When resuming a crawl from a job directory, feeds whose URI uses
%(batch_id)dnow continue the batch numbering of the previous run, instead of starting from 1 again and overwriting the existing files. (#5153, #7650, #7656)Item exporters now serialize nested items, and lists of them, using the serializers declared in their own fields. (#3888, #3890, #8057)
Fixed
AsyncioLoopingCallsometimes calling its function twice in a row when the event loop woke it up slightly early, which could, for example, close a spider because ofCLOSESPIDER_TIMEOUT_NO_ITEMwhile it was still producing items. (#8294)The RobotFileParser parser now ignores the invalid bytes of a
robots.txtfile that is not valid UTF-8, like the other built-in parsers, instead of ignoring the whole file. (#8316)Exceptions raised while handling the output of a spider callback, e.g. by a custom scheduler or log formatter, are now logged, and no longer interfere with the handling of the rest of that output. (#8318)
Scrapy now uses the event loop of the installed asyncio reactor when no event loop is running, instead of the current event loop of the thread, which can be a different one or none at all, e.g. when the reactor was installed with a loop that is not set as the current one. (#7201, #8324, #8325)
Stopping a crawl while an item yielded from
start()is going through the item pipelines no longer hangs. (#8348)H2DownloadHandlernow fails requests with the connection error when it cannot connect to the server, instead of letting them hit the download timeout, and later requests to the same server try to connect again. (#8332)Fixed
ScrapyPriorityQueue, which the defaultDownloaderAwarePriorityQueueuses for each download slot, returning no request or a request other than the one that itspeek()method returned, which could happen with requests of the same priority in its start request and regular request queues, or after a request failed to be serialized into a disk queue. (#7837)The telnet console, and any other caller of
scrapy.utils.reactor.listen_tcp(), now tries the next port when another process starts listening on the same port at the same time, instead of failing to start. (#8356)Fixed
RobotsTxtMiddlewareletting through requests disallowed byrobots.txtwhen they were sent while therobots.txtfile of their website was being downloaded for another request. (#8297, #8386)SitemapSpidernow only treats links withrel="alternate"as alternate links, instead of any link, e.g. canonical ones, both whensitemap_alternate_linksis enabled and in the entries passed tositemap_filter(). (#8390)Download handlers are now closed when the engine is closed without having been started, e.g. when opening the spider fails, and the downloader is now closed when the engine is stopped without a spider. (#8167, #8377)
The spider is no longer considered idle, and so no longer closed, while a request taken from the scheduler has not reached the downloader yet, which could happen with a custom
DOWNLOADER. (#8315, #8355)The reactorless
shellnow waits for the engine to start before letting you use it. (#8168)On Windows,
AiohttpDownloadHandlerno longer connects to the wrong port in rare cases. (#8382)The Scrapy
shellno longer uses ptpython on Windows when the standard output is not a console, which ptpython does not support. (#8367)
Documentation
Documented how blocking code in callbacks and other components slows down downloads and inflates their
download_latency. (#3197, #8160)Documented how to change concurrency and delays from the telnet console on a running crawl. (#4196, #8164)
Documented that the
open_spider()andclose_spider()methods of item pipelines run concurrently, and onlyprocess_item()follows theITEM_PIPELINESorder. (#2645, #8158)Documented how to set up a development environment to contribute to Scrapy. (#4451, #8165)
Moved the release notes of Scrapy 2.13 and older into separate pages per major version. (#8150)
Documented how to extract clean content and parse values, how to sign requests with OAuth, how to deduplicate repeated query string parameters in request fingerprints, and that retried status codes should also be in
HTTPCACHE_IGNORE_HTTP_CODES. (#40, #1113, #2297, #8190, #8202, #8208, #8209)Improved the API reference of
SitemapSpider,XMLFeedSpiderandCSVFeedSpider. (#8229, #8239)Documented the order of the
spider_opened,engine_started,spider_closedandengine_stoppedsignals. (#1523, #8101)Documented that the
JOBDIRandHTTPCACHE_DIRdirectories must be protected from write access by untrusted parties. (#8252)Documented how to write custom feed storage backends and the built-in feed storage backend classes. (#7800)
Added an introduction video to the page about coding agents. (#8253)
CrawlSpiderandRuleare now documented through their docstrings, and the documentation now recommendsSpideroverCrawlSpiderfor crawls that do not fit its declarative rules. (#7025, #8240)Documented the
open_spider_async(),start_async(),close_spider_async()andstop_async()methods of the execution engine. (#6164, #8462)Documented how to write asyncio code that also supports older Scrapy versions, and the documentation now recommends
asyncio.to_thread()to call blocking code from coroutines. (#7956, #8454)Reviewed the documentation of
Spider, which now covers all its attributes, includingstate. (#7025, #7811)Updated the installation guide, and documented what to do when installing a dependency fails. (#5308, #7878)
The tutorial now shows how to crawl
quotes.toscrape.comfaster withDOWNLOAD_SLOTS. (#8334)Documented
HttpError, the IPv6 support of the built-in download handlers, thebootstrap_failedattribute of crawler processes, and where exceptions that interrupt a crawl started from a script reach your code. (#8338, #8340, #8344)Added a page about getting help. (#3688)
Documented that high values of
CONCURRENT_REQUESTSmay exceed the limit of open file descriptors that the operating system sets, and how to raise that limit. (#5259, #5272)Other documentation improvements and fixes. (#5859, #7114, #8151, #8161, #8314, #8403, #8404, #8436, #8453)
Quality assurance
Improved and fixed type hints. (#7811, #8078, #8183, #8311, #8333, #8440)
Improved the documentation build and the contributor tooling, including an
AGENTS.mdfile for coding agents. (#8011, #8154, #8157, #8188, #8212, #8214, #8216, #8219, #8238, #8251, #8364, #8384, #8409, #8411)CI and test improvements and fixes. (#6141, #7949, #8127, #8155, #8156, #8194, #8223, #8228, #8231, #8232, #8233, #8235, #8236, #8258, #8273, #8274, #8275, #8276, #8277, #8278, #8279, #8280, #8281, #8286, #8300, #8301, #8311, #8314, #8317, #8320, #8351, #8359, #8360, #8361, #8372, #8374, #8375, #8381, #8387, #8388, #8389, #8406, #8412, #8423, #8444)
Scrapy 2.19.0 (2026-09-10)
Highlights:
New
RemoteControlextension which allows inspecting and controlling a running crawl over HTTP, used by the Scrapy MCP serverExperimental
aiohttp-based download handler (now the default when running without a reactor)
Modified requirements
Added support for Python 3.15. (#7511)
New dependencies:
aiohttp >= 3.13.3
charset-normalizer >= 3.4.0
platformdirs >= 2.0.0
Backward-incompatible changes
When running without a Twisted reactor, i.e. with
TWISTED_REACTOR_ENABLEDset toFalse, the default download handler forhttpandhttpsis nowAiohttpDownloadHandlerinstead ofHttpxDownloadHandler. You can configureHttpxDownloadHandlerin theDOWNLOAD_HANDLERSsetting if you want. (#8118)scrapy.http.cookies.WrappedRequest.is_unverifiable()now always returnsFalse, and the undocumentedis_unverifiablerequest meta key that it used to read is ignored. (#7933)
Deprecations
The
RANDOMIZE_DOWNLOAD_DELAYsetting is deprecated. Use the newDOWNLOAD_DELAY_JITTERsetting instead. Similarly, therandomize_delaykey of theDOWNLOAD_SLOTSsetting is deprecated in favor of a newjitterkey, therandomize_delayattribute ofscrapy.core.downloader.Slotis deprecated in favor of its newjitterattribute, and therandomize_delayattribute ofscrapy.core.downloader.Downloaderis deprecated in favor of theDOWNLOAD_DELAY_JITTERsetting. (#7881)The
install_root_handlerparameter ofconfigure_logging(),CrawlerProcessandAsyncCrawlerProcessis deprecated. Use the newLOG_INSTALL_ROOT_HANDLERsetting instead. (#4793, #8041)The
scrapy.dupefilters.RFPDupeFilter.fingerprintsattribute is deprecated. Overridingscrapy.dupefilters.RFPDupeFilter.request_fingerprint()is deprecated as well; set theREQUEST_FINGERPRINTER_CLASSsetting instead. (#5517, #7943)Overriding the
add_pre_hook()oradd_post_hook()methods ofContractis deprecated. Definepre_process()orpost_process()instead. (#6681, #7886)
New features
Added a
RemoteControlextension, enabled by default, which allows connecting to crawl processes via HTTP and running code inside them. (#7866)Added an experimental HTTP download handler based on aiohttp,
AiohttpDownloadHandler. (#8118)Added SQLite-backed scheduler queues:
PickleFifoSQLiteQueue,PickleLifoSQLiteQueue,MarshalFifoSQLiteQueueandMarshalLifoSQLiteQueue. They write each request within its own transaction, so that an unclean shutdown cannot corrupt the on-disk queue, at the cost of slower scheduling. (#845, #7877)Added a
DOWNLOAD_DELAY_JITTERsetting, and ajitterkey forDOWNLOAD_SLOTS, which set the magnitude of the random variation applied toDOWNLOAD_DELAY. They replace theRANDOMIZE_DOWNLOAD_DELAYsetting and therandomize_delaykey, which could only toggle a fixed ±50%. (#7881)Added a
LOG_COLORsetting, which colorizes log output by log level when logging to a terminal. It needs the new color extra. (#8091)The encoding of a response that doesn’t declare one is now detected with charset-normalizer when the response body is neither ASCII nor UTF-8, instead of always falling back to
cp1252. (#3135, #8054)Added a
LOG_INSTALL_ROOT_HANDLERsetting, which replaces the deprecatedinstall_root_handlerparameter and, unlike it, can also be set from asettings.pymodule or from the command line. (#4793, #8041)Contracts now support callbacks defined with
async def, including asynchronous generators. (#6681, #7886)Added the
MethodContract(@method),BodyContract(@body),HeaderContract(@header) andCookieContract(@cookie) contracts, which set the corresponding attributes of the sample request, and an-aoption for thecheckcommand, to set spider arguments as in thecrawlcommand. (#1918, #8053)Added
Response.to_dict(),Response.from_dict()andresponse_from_dict(), and used them in the built-in HTTP cache storages, which now restore cached responses of any response class, including those of third-party plugins, with all their attributes. (#1450, #7908)Cached responses now indicate when they were stored, through the new
cache_timestamprequest meta key. (#2221, #8034)The
formatkey ofFEEDSis now inferred from the file extension of the feed URI when not set, e.g.jsonfor a URI ending in.json. (#1158, #8031)Added
find_projects(), which yields the root directory of every Scrapy project in a directory tree. (#8024)Added a public
schedulerattribute toExecutionEngine. (#8099)StatsCollectorobjects now implement__str__(), which returns the pretty-printed stats. (#2746)open_in_browser()now also supports responses that are neither HTML nor plain text, picking a file extension based on theContent-Typeheader. (#3902, #8067)The
-t/--templateoption of thegenspidercommand now also takes a path to a.tmplfile, so that a custom template can be used without settingTEMPLATES_DIR. (#8071)The
--pdbcommand-line option now uses ipdb instead ofpdbwhen ipdb is installed. (#4284, #8052)Log records about item processing, i.e. about items scraped, dropped or raising an exception, now carry the item in their
extradict, under theitemkey, so that custom logging handlers can read it. (#8085)
Improvements
RFPDupeFilternow keeps request fingerprints asbytes, to reduce memory usage. Therequests.seenfile that it writes in the job directory is now a binary file. (#5517, #7943)The
--pdbcommand-line option now starts a post-mortem debugging session on every logged error that comes with a traceback, instead of on everyFailureobject built anywhere in the process. (#3552, #8037)The Scrapy
shellno longer prints theDEBUGmessages of parso, an indirect dependency of IPython, whenLOG_LEVELisDEBUG. (#8060)Other code refactoring and improvements. (#8123)
Bug fixes
HTTP11DownloadHandlernow setscertificateandip_addressattributes even for responses without a body. (#4466, #8048)HTTP connection pool keys in
HTTP11DownloadHandlerandH2DownloadHandlernow include the request bind address (seeDOWNLOAD_BIND_ADDRESS), so that requests bound to different addresses no longer reuse each other’s pooled connections. (#3565, #8081)HttpCacheMiddlewarenow updates the headers of a cached response, and stores it again, when a revalidation request gets a 304 response. (#3778, #8068)An exception raised in a spider callback that no
process_spider_exception()method handles is now offered to each of those methods only once. (#4729, #7996)Defining
allowed_domainsas a property no longer breaks the commands that match a URL to a spider, i.e.shell,fetchandparse. A property cannot be evaluated on a spider class, so it is now ignored, with a warning, instead of raisingTypeError. (#3119, #8094)get_project_settings()now adds the project directory tosys.pathalso when theSCRAPY_SETTINGS_MODULEenvironment variable is set, so that the settings module that the variable points to can be imported. (#4780, #8042)scrapy.utils.datatypes.LocalCacheno longer evicts the oldest item when updating an existing one. (#8113)
Documentation
Added a page about using Scrapy with coding agents, covering the official agent plugin and the Scrapy MCP server. (#8120)
Documented the request metadata keys that were missing from the list of special keys, and documented that keys whose name starts with an underscore are internal. (#3585, #5564, #7933)
Documented how to write custom Scrapy commands, how to write custom spider templates, how to access the response of a failed media download and how to set request headers for media pipeline requests. (#2046, #2504, #3056, #6844, #6904, #8049, #8056, #8063)
Documented how to subclass
RedirectMiddlewareto allow or deny redirects based on the target URL, and how to set the priority of the requests thatCrawlSpidergenerates from its rules. (#3613, #4009, #8061, #8070)Documented that
get_project_settings()returns project settings only, that spiders running concurrently in the same process get independent crawlers, middlewares and settings, and that Scrapy sets therequestattribute of theFailureobjects that it passes to errbacks. (#2378, #4253, #6408, #7901, #8051, #8055)Documented
ScrapyCommandandStatsCollector. (#6844, #6904, #8072)Improved the contents of
llms-full.txtand Markdown versions of documentation pages. (#8083, #8087, #8088, #8089, #8117, #8119)
Quality assurance
Scrapy 2.18.0 (2026-08-20)
Highlights:
HttpxDownloadHandlernow uses httpx2The Twisted-based HTTP/2 download handler is no longer experimental
brotliand Zstandard support are now always available, and optional extras cover the rest of the optional featuresLate
Crawlerattributes, such asstats, now raiseRuntimeErrorinstead of beingNonebefore the crawl startsItem exporters now export fields in declaration order
New optimization page and built-in stats reference
Modified requirements
brotli(brotlicffion PyPy) and Zstandard support (the standard librarycompression.zstdmodule on Python 3.14 and higher, thebackports.zstdpackage on earlier versions) are now required, sobrandzstdare always included in theAccept-Encodingheader of requests, and Brotli- and Zstandard-compressed responses are always decoded. Websites may now serve such responses to crawls that previously did not advertise support for them.The minimum required versions are
brotli1.2.0,brotlicffi1.2.0.0 andbackports.zstd1.3.0.Increased the minimum versions of the following dependencies:
cryptography: 37.0.0 → 41.0.5
pyOpenSSL: 22.0.0 → 24.3.0
queuelib: 1.4.2 → 1.6.1
service_identity: 23.1.0 → 24.2.0
w3lib: 1.17.0 → 2.1.1
The IPython shell requires IPython 8.15.0 or higher. Install the ipython extra to get a compatible version. (#5447, #7596, #7816)
Backward-incompatible changes
The following runtime usage of zope.interface interfaces is removed:
SpiderLoaderandDummySpiderLoaderare no longer marked as implementing theISpiderLoaderinterface.get_spider_loader()no longer checks that the configured spider loader implements theISpiderLoaderinterface.BlockingFeedStorage,FileFeedStorageandStdoutFeedStorageare no longer marked as implementing theIFeedStorageinterface.H2DownloadHandlerno longer checks that theDOWNLOADER_CLIENTCONTEXTFACTORYclass implements theIPolicyForHTTPSinterface.
The
engine,extensions,logformatter,request_fingerprinterandstatsattributes ofCrawlerraiseRuntimeErrorwhen read before the crawl starts, instead of beingNoneuntil then.Code that reads them from the
spider_openedsignal handler onwards is unaffected, and no longer needs to narrow their type. Code that checked whether they were set, e.g.if crawler.stats:, must be updated, since reading them now raises instead of returningNone.Item exporters now export the fields of an item in declaration order, i.e. the order in which they are defined in the item class, instead of the order in which they were populated, as
CsvItemExporteralready did.dictitems, which have no declared fields, keep using the key order of each item. (#6662, #6854, #7824)scrapy.utils.serialize.ScrapyJSONEncoder, used by JSON feed exports, the telnet console and thePeriodicLogextension, now serializesdatetime,dateandtimeobjects in ISO 8601 format, e.g.2023-08-03T23:24:57.148903+00:00instead of2023-08-03 23:24:57, keeping microseconds and time zone information.Its
DATE_FORMATandTIME_FORMATattributes are removed.scrapy.utils.trackref.live_refsis now aWeakKeyDictionaryinstead of acollections.defaultdict, so that classes defined at run time are released once they are no longer used. Reading the entry of a class with no tracked instances now raisesKeyErrorinstead of creating and returning an empty mapping. (#5995, #7922)The
MEMDEBUG_NOTIFYsetting is removed. It had no effect, but code reading it now getsNoneinstead of its default value, which was an empty list. (#7737)scrapy.utils.log.logformatter_adapter()no longer passes the wholedictreturned by a log formatter method as logging arguments when thatdicthas noargskey, or itsargsare empty, and itsmsghas no%(name)splaceholders. Such messages are now logged verbatim, so a literal%in them no longer breaks logging.An
argstupleis now expanded into one logging argument per item, so that%-style placeholders work with it as they do with adict.FEEDSkeys andFEED_URIvalues that arepathlib.Pathobjects are now used as paths, instead of being converted intofile://URIs. This makes them keep working when they contain URI parameters or characters that URI conversion would percent-encode. (#5794, #6425, #6611, #7674)SelectorandTextResponse.selectorno longer force thehtmlselector type for responses that are neitherHtmlResponsenorXmlResponseobjects. AJsonResponsegets thejsontype, and for any other responseparseldetermines the type from the body.The response class, and hence the selector type, comes from the content type that the website reports. When a website reports the wrong content type, recast the response, e.g.
response.replace(cls=HtmlResponse).AutoThrottle no longer sets the
download_delayattribute of the running spider to define the starting delay of download slots. The starting delay is still applied, but code that reads that attribute at run time no longer sees it. (#7167, #7175, #7833)The
checkcommand now ignoresITEM_PIPELINESandFEEDS, since contracts check the output of callbacks instead of sending it to item processing, so a check run no longer triggers their side effects, e.g. writing an empty output file. Use the-scommand-line option to set them back for a check run. (#3385, #7957)XMLFeedSpiderandCSVFeedSpiderno longer raiseNotConfiguredwhenparse_node()orparse_row()is not defined; the resultingAttributeErroris reported instead. (#7768)
Deprecation removals
scrapy.utils.misc.md5sum(), deprecated since Scrapy 2.12.0, is removed. (#6264, #8023)scrapy.utils.iterators.xmliter(), deprecated since Scrapy 2.11.1 because it is vulnerable to ReDoS attacks, is removed. Usexmliter_lxml()instead. (#7765)scrapy.utils.datatypes.CaselessDict, deprecated since Scrapy 2.10.0, is removed. UseCaseInsensitiveDictinstead. (#5146, #8023)
Deprecations
The
download_delayspider attribute is deprecated. Use theDOWNLOAD_DELAYsetting, orDOWNLOAD_SLOTSto set a delay for specific domains, instead.The
max_concurrent_requestsspider attribute, deprecated since Scrapy 2.14.0, now sets theCONCURRENT_REQUESTS_PER_DOMAINsetting, which is what it always mapped to, and warns accordingly.Both attributes are ignored, with a different warning, when the corresponding setting is already set at the
spiderpriority or higher.The
Spider.log()method is deprecated. Use the methods ofSpider.loggerinstead. (#7739)The
scrapy.interfacesmodule and itsISpiderLoaderinterface are deprecated. Custom spider loaders only need to followSpiderLoaderProtocol. (#6585, #7731)scrapy.extensions.feedexport.IFeedStorageis deprecated. Custom feed storages only need to followscrapy.extensions.feedexport.FeedStorageProtocol. (#6585, #7731)scrapy.utils.python.re_rsearch()is deprecated. (#7765)Importing
FileExceptionfromscrapy.pipelines.filesis deprecated. Import it fromscrapy.pipelines.mediainstead. (#7544, #7673, #7973)Setting
request.meta["is_secure"]toFalseto send ans3://request over plaintext HTTP is deprecated. The flag will be ignored in a future Scrapy version. (#7738)The unused
multiplierattribute ofPeriodicLogis deprecated. (#7809, #7982)Returning, from a log formatter method, a
msgwith%(name)splaceholders and noargsis deprecated. Those placeholders are still interpolated with the returneddict, but in a future Scrapy version the message will be logged verbatim. Return those values underargsinstead. (#5570, #7971)
New features
Added optional extras for every optional dependency of Scrapy:
bpython,gcs,httpx,images,ipython,ptpython,robotparser,s3,twisted-http2anduvloop. For example,pip install scrapy[s3,images]. (#7596)HttpxDownloadHandlernow uses httpx2, the successor ofhttpx, which the new httpx extra installs together with its HTTP/2 and SOCKS proxy support.httpxis still used whenhttpx2is not installed, but it is no longer tested. (#7762)Added a
robots_parsedsignal, sent byRobotsTxtMiddlewareafter it parses arobots.txtfile. It supports asynchronous handlers.Added a
crawl_delay()method toRobotParser, implemented by all built-in robots.txt parsers.(#7830)
Added a
Request.to_curl()method, the inverse offrom_curl(). (#7743, #7746, #7802)Added a
depth_resetrequest meta key that gives a request depth 0 instead of the depth of its source response plus 1. (#891, #7913)Added
MetaCopyDetectionMiddleware, enabled by default, which warns once per crawl when a spider yields a request carrying internalmetakeys that were likely copied fromresponse.meta, and aMETA_COPY_WARN_SKIP_KEYSsetting to exclude keys from that check. (#7588)Added an
AWS_MAX_POOL_CONNECTIONSsetting, which defines the connection pool size of the AWS clients of the S3 feed storage backend and the S3 media pipeline storage backend, and defaults toREACTOR_THREADPOOL_MAXSIZE. It is also exposed as amax_pool_connectionsparameter ofS3FeedStorageand as anAWS_MAX_POOL_CONNECTIONSattribute ofS3FilesStore. (#4985, #7794)Added a
scrapy.utils.asyncio.sleep()function, which works both with and without a Twisted reactor. (#7843)CONCURRENT_REQUESTScan now be set to0for no limit. (#7840)H2DownloadHandleris no longer experimental, and it now sends thebytes_receivedandheaders_receivedsignals and supportsStopDownload. (#5046, #5047, #5055, #7896, #7986)An exception raised by
Spider.start()is now reported through thespider_errorsignal and thespider_exceptions/countandspider_exceptions/{exception}stats, and closes the spider with the newstart_errorfinish_reasoninstead offinished. See Handling start errors.CloseSpiderraised fromSpider.start()now closes the spider with the given reason, instead of being reported as a start error.CloseSpidercan now also be raised while the spider is starting, e.g. from aspider_openedsignal handler or from theopen_spider()method of an item pipeline, to close the spider before it starts crawling. Every component still gets started, and stopped, before the spider is closed with the given reason. (#3435, #7905)Added an FTPS feed storage backend, i.e. support for the
ftpsURI scheme inFEEDS, which uploads the feed over a TLS connection, verifying the certificate of the server. (#4180, #7953)Changes to
Spider.allowed_domainsduring a crawl are now taken into account byOffsiteMiddleware, whoseshould_follow()method is now documented as the way to implement a different offsite policy. (#3257, #3412, #7903, #7912)BaseSettingsmethods that take settings, such asupdate()and thesettingsparameter of crawler classes, now also accept an iterable of(name, value)tuples. (#7759, #7763)The
cookiesparameter ofRequestnow also acceptsbool,floatandintvalues, and theformdataparameter ofFormRequestnow accepts any mapping or iterable of key-value pairs. (#7858, #7864)Added a
scrapy.utils.reactorless.uninstall_reactor_import_hook()function, whichAsyncCrawlerProcess.start()now uses to uninstall thetwisted.internet.reactorimport hook when it exits. (#7747)Added the
depth/request_ignored_countandhttpcache/retrieve_errorstats. (#1308, #2222, #7805, #7916)The
get_serialized_fields()method of item exporters, previously named_get_serialized_fields(), is now public and documented, for custom item exporters to use. (#5706, #7931)Scrapy now writes the session keys of its HTTPS connections to the file that the
SSLKEYLOGFILEenvironment variable points to, so that traffic analysis tools such as Wireshark can decrypt them. See Decrypting TLS traffic. (#4368, #7948)Added an
HTTP2_MAX_FRAME_SIZEsetting, which allows raising the maximum HTTP/2 frame size that servers may send, previously fixed at 16384, above which connections failed. (#5050, #7988)The
crawl,parseandrunspidercommands now warn whenFEEDSis set, e.g. through-oor-O, but theFeedExporterextension is disabled, so that no item is exported. (#5970, #6082, #6373, #7902)Log formatters (
LOG_FORMATTER), item processors (ITEM_PROCESSOR) and robots.txt parsers (ROBOTSTXT_PARSER) are now built as components, so they no longer need afrom_crawler()method. (#7808)
Bug fixes
HttpCacheMiddlewarenow logs a warning and handles the request as a cache miss when reading a cache entry raises an exception, e.g. because the entry is corrupted, instead of letting the exception propagate. It also counts those entries in the newhttpcache/retrieve_errorstat. (#2222, #7805)Feed URIs now only expand
%(...)sparameters, keeping any other percent character as is, so that percent-encoded URIs, e.g. one with%20in a path or with percent-encoded FTP credentials, are no longer misinterpreted as printf-style formatting directives. (#5794, #6425, #7674)Feed exports now start storing a
FEED_EXPORT_BATCH_ITEM_COUNTbatch as soon as it is complete, instead of waiting until the spider closes. (#7730, #7733)CsvItemExporternow warns when the fields that it took from the first item do not cover the fields of a later item, i.e. when it silently drops data. (#4002, #4053, #7613, #7651)GCSFeedStorageno longer requires thestorage.buckets.getpermission. (#5475, #7945)Media pipelines now log media requests that were filtered out, e.g. as offsite requests, at the
DEBUGlevel and without a traceback, instead of reporting them as download errors. (#7544, #7673)OffsiteMiddlewarenow raisesIgnoreRequestwith a message, e.g.Filtered offsite request to 'offsite.example', which errbacks and log messages that report that exception now include. (#7544, #7673)HTTP11DownloadHandlernow skips response header lines that have no colon, logging them at theDEBUGlevel, as web browsers do, instead of being unable to download such a response at all. (#210, #7806)CookiesMiddlewarenow sends domain cookies to hosts without a dot in their name and to hosts given as an IP address. (#6410, #7900)TextResponse.json()now decodes bodies that are not valid UTF-8, UTF-16 or UTF-32 usingTextResponse.encoding, instead of raisingUnicodeDecodeError. (#6456, #7897)scrapy.resolver.CachingHostnameResolvernow caches addresses without a port, and sets the requested port on cache hits, so that a cached address no longer carries the port of the request that populated the cache. (#6442, #7772)DownloaderAwarePriorityQueuenow removes the directory of a download slot from theJOBDIRdirectory once that slot is drained. (#5275, #7955)TelnetConsoleno longer raises an exception on shutdown when it could not listen on any of theTELNETCONSOLE_PORTports. (#2702, #7910)The
DOWNLOAD_WARNSIZEwarning is no longer logged twice for a response whoseContent-Lengthheader already exceeded the limit. (#2476, #7963)HttpCompressionMiddlewarenow logs a warning when it drops a response for exceedingDOWNLOAD_MAXSIZEduring decompression. (#6616, #7742)DepthMiddlewarenow logs only the first request ignored for exceedingDEPTH_LIMIT, and counts them all in the newdepth/request_ignored_countstat. (#1308, #7916)parsenow sets the callback it uses on the request of the response it passes to that callback. (#3095, #3124, #7803)The IPython shell now works when an asyncio event loop is already running in the same thread, e.g. when calling
scrapy.shell.inspect_response()from a callback while using the asyncio reactor. (#5447, #7816)Request.from_curl()now merges repeated-d,--dataand--data-rawoptions into a single body joined with&, as curl does, instead of keeping only the last one. (#7728)The
copy()method and the|=operator ofscrapy.utils.datatypes.CaseInsensitiveDictno longer leave the internal mapping of original key spellings shared or out of date. (#7783)ExecutionEngine.download_async()no longer recurses once per returned request, e.g. once per redirect. (#7544, #7673)LinkExtractornow canonicalizes each extracted URL once instead of twice whencanonicalizeisTrue. (#7961)Items yielded from
Spider.start()now keep the spider busy until the item pipelines are done with them, so that a spider that only yields items fromstart()no longer closes before processing them. (#7029, #7891)open_in_browser()now also adds itsbasetag to HTML responses that have noheadelement, and it now overrides abasetag already present in the response, so that relative URLs resolve against the response URL in every case. (#6550, #7879)Spider.start()implementations that are not asynchronous generators now raiseTypeErrorwith a message that says so, instead of failing in a way that does not point at the cause. (#5426, #7946)The
check,fetchandparsecommands now return the exit code 1 when a component fails to initialize, ascrawlandrunspideralready did. (#4292, #7920)HttpCompressionMiddlewareno longer hangs on adeflateresponse body followed by extra bytes. (#7841)scrapy.utils.python.get_func_args()now reports the parameters that afunctools.partialobject binds by position, instead of an empty list. (#7841)Fixed
NameErrorexceptions on Python 3.14, where PEP 649 made annotation evaluation lazy, when inspecting the signature of a callable with annotations imported only for type checking. (#7796, #7818)scrapy.utils.decorators.deprecatedcan now be used both as@deprecatedand as@deprecated(...)without confusing type checkers. (#7797)The default download handlers can now download from domains with emoji characters or underscores, which were previously rejected. (#3321, #4330, #7846)
Callbacks and media pipeline results no longer wait 100 ms before proceeding. (#8019)
Shutting down a crawl no longer risks raising an unhandled
RuntimeErrorif the code interrupted by the shutdown signal was itself writing to the log. (#8022)Nested selectors, e.g. the result of calling
jmespath()on a selector, now letparseldetermine their type instead of forcing thehtmltype, so that they no longer return the wrong type or value. (#8038, #8040)
Documentation
Added a built-in stats reference, covering every stat that Scrapy sets. (#6351, #7814)
Replaced the broad crawls page with a new optimization page, about finding the bottleneck of a crawl before changing any setting, which covers broad crawls as one of its sections. (#4737, #7938)
Added a concepts page, a quick map of Scrapy’s main building blocks, what problem each one solves, and when to reach for it. (#1569, #8025)
Added a cookies page, which gathers what used to be spread across the request and downloader middleware pages. (#7947)
Added callbacks and errbacks sections to the request and response page, covering callback assignment, how to write a callback and supported callback output. (#5054, #6437, #7821, #7898)
Documented the
ITEM_PROCESSORsetting and theItemProcessorProtocolprotocol that its value must implement. (#7983)Documented how to write an item exporter, how to test an item pipeline, how to download a request from a downloader middleware, how to name media files after the response, how to add objects to the shell and how to run spiders inside an existing application or in a Jupyter notebook. (#915, #1199, #2594, #5706, #6554, #6594, #7751, #7872, #7876, #7889, #7909, #7931)
Added an inspecting live traffic section to the debugging page, covering Wireshark and mitmproxy. (#5222, #8007)
Documented how
TextResponseresolves the response encoding, and how to resolve it differently, e.g. to give the encoding declared in the response body precedence over theContent-Typeheader. (#4933, #7977)Documented the memory use of response parsing and the parser limits that Scrapy lifts, in the security page. (#5700, #7930)
Documented that signal handlers run in an undefined order, that
scheduler_emptymust only be awaited fromstart(), that concurrency and politeness settings apply per crawler when running multiple spiders in the same process, and that aJOBDIRdirectory cannot be shared across Scrapy versions. (#3191, #5330, #5522, #7861, #7883, #7907, #7941)Documented that the
htmliterator ofXMLFeedSpidercan silently mangle tags that HTML treats as void elements, e.g.<link>, dropping their content and closing tag. (#4675, #8045)Documented that the
keep_fragmentsparameter offingerprint()is not a substitute for rendering JavaScript to reach content that a headless browser loads based on the URL fragment. (#4789, #8033)Documented how to derive the job directory from the spider name. (#4748, #8035)
Documented that the project name from
scrapy.cfgalso appears elsewhere by default, and which of those uses actually require it to match. (#2484, #8044)Many other corrections and improvements. (#4589, #4796, #5532, #5548, #6053, #6184, #6627, #6787, #6943, #6989, #7710, #7725, #7737, #7767, #7769, #7771, #7774, #7775, #7777, #7779, #7780, #7817, #7832, #7835, #7862, #7871, #7875, #7880, #7890, #7903, #7913, #7917, #7939, #7940, #7962, #7965)
Quality assurance
Improved and fixed type hints. (#7712, #7785, #7858, #7864, #7865, #7867)
Added CPU benchmarks, tracked on CodSpeed, so that performance regressions are caught before they are merged and performance work can be measured. (#7831, #7839, #7870, #7887, #7914, #7954)
Added a nightly job that runs the test suite against the development branches of dependencies, so that incompatibilities are found before those dependencies are released. (#5291, #6025, #7924, #7960)
CI and test improvements and fixes. (#5049, #5620, #5837, #6478, #6794, #7262, #7437, #7702, #7720, #7724, #7727, #7736, #7741, #7749, #7753, #7755, #7768, #7778, #7782, #7792, #7793, #7795, #7797, #7798, #7809, #7829, #7834, #7836, #7838, #7841, #7844, #7848, #7853, #7854, #7857, #7859, #7863, #7895, #7906, #7928, #7935, #7966, #7968, #7974, #7979, #7985, #7990, #7993, #7995, #8000, #8001, #8002)
Scrapy 2.17.0 (2026-07-07)
Highlights:
Security bug fixes
HTTP/2 and SOCKS proxy support for
HttpxDownloadHandlerImproved settings for changing allowed TLS versions
Security bug fixes
s3://requests now use HTTPS by default, instead of plaintext HTTP.Previously,
S3DownloadHandlersent signed S3 requests over plaintext HTTP unlessrequest.meta["is_secure"]was set to a true value, exposing the request path, the AWSAuthorizationheader, theX-Amz-Security-Tokenheader (when using temporary credentials), and the response contents to network attackers, who could also tamper with responses. See the 76g3-c3x4-crvx security advisory for details.To restore the previous behavior for a given request, set
request.meta["is_secure"]toFalse.
Deprecations
The
DOWNLOADER_CLIENT_TLS_METHODsetting is deprecated. You should use theDOWNLOAD_TLS_MIN_VERSIONand/orDOWNLOAD_TLS_MAX_VERSIONsettings instead if you want to change the TLS method selection. (#3288, #6546)The following spider attributes are deprecated in favor of settings:
http_user(useHTTPAUTH_USER)http_pass(useHTTPAUTH_PASS)http_auth_domain(useHTTPAUTH_DOMAIN)
(#7590)
The
scrapy.commands.ScrapyCommand.help()method is deprecated. It was never called by Scrapy. (#7626, #7633)The following TLS-related functions and constants, intended for internal use, are deprecated:
scrapy.core.downloader.tls.METHOD_TLSscrapy.core.downloader.tls.METHOD_TLSv10scrapy.core.downloader.tls.METHOD_TLSv11scrapy.core.downloader.tls.METHOD_TLSv12scrapy.core.downloader.tls.openssl_methodsscrapy.core.downloader.tls.DEFAULT_CIPHERSscrapy.utils.ssl.ffi_buf_to_string()scrapy.utils.ssl.get_temp_key_info()scrapy.utils.ssl.x509name_to_string()
The
CRAWLSPIDER_FOLLOW_LINKSsetting is deprecated. You can setfollow=Falsein your rules to achieve the same effect. (#7592)Instantiating
HttpCompressionMiddlewarewithout acrawlerargument is deprecated. (#7655)Instantiating
RefererMiddlewarewithout asettingsargument is deprecated. (#7664)
New features
Added support for HTTP/2 requests to
HttpxDownloadHandler. It requires setting the newHTTPX_HTTP2_ENABLEDsetting toTrue. (#7575)Added support for SOCKS proxies to
HttpxDownloadHandler. (#747, #7575)Added
DOWNLOAD_TLS_MIN_VERSIONandDOWNLOAD_TLS_MAX_VERSIONsettings as replacements for theDOWNLOADER_CLIENT_TLS_METHODsetting (which is now deprecated). Compared to the old setting, they support specifying a range of allowed versions and support newer TLS versions. (#4821, #6546)Added
HTTPAUTH_USER,HTTPAUTH_PASSandHTTPAUTH_DOMAINsettings andhttp_user,http_passandhttp_auth_domainmeta keys as more flexible ways to set HTTP authentication data. (#7590)Added a
verbatim_urlmeta key that can be set toTrueto skip request URL canonicalization. (#7473)Added
deny_tagsanddeny_attrsarguments toLinkExtractor. (#6321, #7679)scrapy.Item.fieldsnow returns the fields in the definition order instead of the alphabetical one. (#7015, #7694)Added a
RETRY_GIVE_UP_LOG_LEVELsetting, agive_up_log_levelmeta key and agive_up_log_levelargument of theget_retry_request()function that allow changing the log level of the message logged when the retry limit has been reached. (#4622, #5297, #7567)It’s now possible to set
DOWNLOADER_CLIENT_TLS_CIPHERStoNoneto use the default ciphers of the underlying TLS implementation. (#7499, #7665)
Improvements
FormRequestis no longer deprecated, only itsfrom_response()method is still deprecated. (#7561, #7671)Switched the item definition in the default project template from a
scrapy.item.Itemto a dataclass. (#7493, #7513)Fixed deprecation warnings with pyOpenSSL 26.3.0. (#7619)
Removed the runtime warnings for
Spider.allowed_domainscontaining URLs or domains with ports instead of just domains and for spider classes having astart_urlattribute instead ofstart_urls. Please use scrapy-lint to find mistakes in your spider code instead. (#4421, #7627)scrapy.utils.test.get_crawler()now disablesTELNETCONSOLE_ENABLEDby default. (#7644)Other code refactoring and improvements. (#7409, #7593, #7594, #7611, #7649)
Bug fixes
HttpxDownloadHandlerno longer ignores proxy credentials for redirected or retried requests. (#7601, #7630)GCSFeedStoragenow closes the temporary file after the upload. (#7546)Fixed
scrapy shell <URL>running a full spider crawl when there is a spider for the requested URL. This bug was introduced in Scrapy 2.13.0. (#7552, #7557)The
IMAGES_STORE_S3_ACLandIMAGES_STORE_GCS_ACLsettings are no longer ignored. This bug was introduced in Scrapy 2.12.0. (#7597, #7614)FTPDownloadHandlernow closes the connection after making the request. (#7602, #7667)Removed the deprecated
spiderargument from the pipeline defined in the default project template. (#7676)When a
Crawlerinstance is passed toAsyncCrawlerRunner.create_crawler()orCrawlerRunner.create_crawler(), settings from both classes are now merged, previously only the settings from theCrawlerinstance were used. (#1280, #7647)Fixed several issues with cookie handling in
scrapy.utils.request.request_to_curl(). (#7603, #7675, #7684)Fixed
scrapy.resolver.CachingThreadedResolvernot disabling the cache whenDNSCACHE_ENABLEDis set toFalse. (#7663)Fixed
scrapy.utils.response.open_in_browser()not removing comments when looking for the<base>tag. (#7506)Fixed checking for deprecated methods in custom
ITEM_PROCESSORimplementations. (#7589)Fixed
scrapy.utils.url.strip_url()corrupting some URLs with credentials. (#7604, #7605)scrapy.utils.misc.rel_has_nofollow()now ignores the case when looking for “nofollow” strings. (#7632)Fixed an exception in
scrapy.utils.sitemap.Sitemapwhen parsing some malformed sitemaps. (#7686, #7687)
Documentation
Mentioned scrapy-lint in the docs. (#4421, #7627)
Added the docs about security considerations. (#7389, #7678)
Improved the item pipeline docs. (#2350, #7676)
Switched documentation examples from using
scrapy.item.Itemto using dataclasses. (#7493, #7513)Added feature comparison tables to the download handler docs. (#7575)
Improved the docs for logging settings. (#6909, #7668)
Documented a way to improve startup time and memory usage by using
SPIDER_MODULES. (#7576, #7600)Clarified handling of the
typeargument ofSelector. (#7704)Other documentation improvements and fixes. (#4954, #6120, #7286, #7564, #7573, #7598, #7599, #7698)
Quality assurance
Fixed deprecation warnings with pytest 9.1.0. (#7621)
CI and test improvements and fixes. (#5954, #7002, #7017, #7247, #7508, #7545, #7566, #7574, #7585, #7595, #7608, #7610, #7612, #7616, #7625, #7637, #7639, #7640, #7641, #7642, #7643, #7644, #7645, #7646, #7654, #7655, #7664, #7672, #7677, #7680, #7682, #7692)
Scrapy 2.16.0 (2026-05-19)
Highlights:
Official support for Python 3.14
Support for Twisted 26.4.0+
Modified requirements
Backward-incompatible changes
The following classes and functions, intended for internal use by
HTTP11DownloadHandlerandH2DownloadHandler, have been made private:scrapy.core.downloader.handlers.http11.ScrapyAgentscrapy.core.downloader.handlers.http11.ScrapyProxyAgentscrapy.core.downloader.handlers.http11.TunnelingAgentscrapy.core.downloader.handlers.http11.TunnelingTCP4ClientEndpointscrapy.core.downloader.handlers.http11.tunnel_request_data()scrapy.core.downloader.handlers.http2.ScrapyH2Agent
Deprecations
scrapy.FormRequestis deprecated. You can use the form2request library instead, see Creating requests that submit HTML forms. (#6438)scrapy.utils.python.MutableChainis deprecated. (#7504)
Deprecation removals
The
start_requests()method ofSpider, deprecated in 2.13.0, is removed and no longer called. Usestart()instead, or both to maintain support for lower Scrapy versions. (#7490)Support for
process_start_requests()methods of spider middlewares, deprecated in 2.13.0, is removed. Useprocess_start()instead, or both to maintain support for lower Scrapy versions. (#7490)Support for synchronous
process_spider_output()methods of spider middlewares, deprecated in Scrapy 2.13.0, is removed. You should upgrade the affected middlewares to have asynchronousprocess_spider_output()methods. (#7504)The
spiderarguments of the following methods ofScraper, deprecated in Scrapy 2.13.0, are removed:close_spider()enqueue_scrape()handle_spider_error()handle_spider_output()
(#7487)
HTTP/1.0 support code, deprecated in Scrapy 2.13.0, is removed. This includes:
scrapy.core.downloader.handlers.http10.HTTP10DownloadHandlerThe
scrapy.core.downloader.webclientmodule.The
DOWNLOADER_HTTPCLIENTFACTORYsetting.
(#7486)
The following functions, deprecated in Scrapy 2.13.0, are removed, you should import them from
w3lib.urldirectly instead:scrapy.utils.url.add_or_replace_parameter()scrapy.utils.url.add_or_replace_parameters()scrapy.utils.url.any_to_uri()scrapy.utils.url.canonicalize_url()scrapy.utils.url.file_uri_to_path()scrapy.utils.url.is_url()scrapy.utils.url.parse_data_uri()scrapy.utils.url.parse_url()scrapy.utils.url.path_to_file_uri()scrapy.utils.url.safe_download_url()scrapy.utils.url.safe_url_string()scrapy.utils.url.url_query_cleaner()scrapy.utils.url.url_query_parameter()
(#7487)
The following test-related code, deprecated in Scrapy 2.13.0, is removed:
the
scrapy.utils.testprocmodulethe
scrapy.utils.testsitemodulescrapy.utils.test.assert_gcs_environ()scrapy.utils.test.get_ftp_content_and_delete()scrapy.utils.test.get_gcs_content_and_delete()scrapy.utils.test.mock_google_cloud_storage()scrapy.utils.test.skip_if_no_boto()scrapy.utils.test.TestSpider
(#7487)
scrapy.utils.versions.scrapy_components_versions(), deprecated in Scrapy 2.13.0, is removed, you can usescrapy.utils.versions.get_versions()instead. (#7487)scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddlewareandscrapy.utils.url.escape_ajax(), deprecated in Scrapy 2.13.0, are removed. (#7487)The
__init__()method of priority queue classes (seeSCHEDULER_PRIORITY_QUEUE) now needs to support a keyword-onlystart_queue_clsparameter, not supporting it was deprecated in Scrapy 2.13.0. (#7487)scrapy.spiders.init.InitSpider, deprecated in Scrapy 2.13.0, is removed. (#7487)
New features
New features and improvements for
HttpxDownloadHandler:Support for proxies.
Support for the
download_latencymeta key.Support for
Response.certificate.Default headers set by the
httpxlibrary are no longer added to requests.
HTTP11DownloadHandlernow skips HTTPS proxy certificate verification when theDOWNLOAD_VERIFY_CERTIFICATESsetting is set toFalse. (#7496)
Improvements
time.monotonic()is used instead oftime.time()to calculate elapsed time in various places. (#7377)Improved extraction of the file extension from the URL in
FilesPipeline. (#4225, #7414)Other code refactoring and improvements. (#7401)
Bug fixes
HTTP11DownloadHandlernow raises an exception when a request has anhttps://destination and anhttps://proxy, which is not supported by this handler. Previously it tried to connect to the proxy via HTTP in this case. (#7496)H2DownloadHandlernow raises an exception for requests withhttp://URLs instead of trying to connect, which is not supported by this handler. (#7496)H2DownloadHandlerno longer adds the:statuspseudo-header toResponse.headers. (#7441)Fixed
scrapy.utils.response.open_in_browser()removing the<head>tag when adding the<base>tag. (#7459)
Documentation
Documented that
HTTP11DownloadHandlerdoesn’t support HTTPS proxies for HTTPS destinations and thatH2DownloadHandlerdoesn’t support proxies at all. (#7496)Added an example of using
logging.handlers.TimedRotatingFileHandlerto rotate Scrapy logs. (#3628, #7501)Mentioned
DOWNLOADER_CLIENT_TLS_METHODin Avoiding getting banned. (#5232, #7518)Other documentation improvements and fixes. (#7417, #7463, #7472, #7480, #7489, #7503, #7507)
Quality assurance
Added tests that connect to https://books.toscrape.com/ to test the behavior with a real website. These tests are marked with the
requires_internetpytest mark and can be skipped with e.g.-m 'not requires_internet'if you cannot or don’t want to run them. (#7520)CI and test improvements and fixes. (#7441, #7466, #7491, #7496)
Scrapy 2.15.2 (2026-04-28)
Bug fixes
Fixed links in https://docs.scrapy.org/llms.txt (#7467)
Scrapy 2.15.1 (2026-04-23)
Bug fixes
Sharing of the SSL context between multiple connections, introduced in Scrapy 2.15.0, is reverted as it caused problems and wasn’t actually needed. (#7445, #7450)
Fixed
scrapy.settings.BaseSettings.getwithbase()failing on keys with dots that aren’t import names. It now works the way it worked before Scrapy 2.15.0, without trying to match class objects and import path. A separate method,get_component_priority_dict_with_base(), was added that does that, and it is now used for component priority dictionaries. (#7426, #7449)
Scrapy 2.15.0 (2026-04-09)
Highlights:
Experimental support for running without a Twisted reactor
Experimental
httpx-based download handler
Backward-incompatible changes
The built-in HTTP download handlers now raise Scrapy-specific exceptions instead of implementation-specific ones, see Exceptions raised by download handlers. This can affect user code that handles downloader exceptions, such as
process_exception()methods of custom downloader middlewares. (#7208)In order to fix a long-standing bug with handling of asynchronous storages, the following changes were made to media pipeline classes, which can impact some of the user code that subclasses them or calls their methods directly:
overrides of
scrapy.pipelines.media.MediaPipeline.media_downloaded()andfile_downloaded()can now return coroutinesmedia_downloaded(),file_downloaded()andimage_downloaded()now return coroutines
RequestandResponseobjects:__slots__and setter changes:scrapy.http.Requestandscrapy.http.Responsenow define__slots__. Assigning arbitrary attributes to instances (for example,response.foo = 1) will raiseAttributeError. Store per-request/response data in the request/responsemetamapping instead of attaching new attributes to the objects.If you maintain custom
RequestorResponsesubclasses that relied on dynamic instance attributes, either add'__dict__'to your subclass__slots__to allow dynamic attributes, or migrate per-instance state tometaor explicit documented attributes.The setters for
headers,flagsandcookiesno longer coerce falsy values intoNone. For example,request.headers = {}now stores an emptyscrapy.http.headers.Headersinstance (notNone), andrequest.flags = []remains an empty list instead of being set toNone. Update code that relied onis Nonechecks or the previous coercion behaviour.
Deprecation removals
The context factory class set as the value of the
DOWNLOADER_CLIENTCONTEXTFACTORYsetting is now required to support themethodargument of__init__(), recommended since Scrapy 1.2.0. (#7353)
Deprecations
scrapy.mail.MailSenderis deprecated. Please usesmtplib,twisted.mail.smtpor other 3rd party email libraries. (#7249, #7263)The
scrapy.extensions.statsmailer.StatsMailerextension is deprecated. You can instead implement your own notifications by handling thespider_closedsignal. (#7249, #7263)The
MEMUSAGE_NOTIFY_MAILsetting is deprecated. You can instead implement your own notifications by handling thememusage_warning_reachedandspider_closedsignals. (#7249, #7263)The
DNS_RESOLVERsetting was renamed toTWISTED_DNS_RESOLVERand the old name is deprecated. (#7350, #7361)The
DOWNLOADER_CLIENTCONTEXTFACTORYsetting is deprecated. If you were using it to switch toscrapy.core.downloader.contextfactory.BrowserLikeContextFactory, please use the newDOWNLOAD_VERIFY_CERTIFICATESsetting instead. If you cannot use the default context factory for some other reason, please subclass the download handler instead. (#7352, #7379)scrapy.core.downloader.contextfactory.BrowserLikeContextFactoryis deprecated. You can set the newDOWNLOAD_VERIFY_CERTIFICATESsetting toTrueinstead. (#7379)The following implementation details of the context factory handling code are deprecated:
scrapy.core.downloader.contextfactory.AcceptableProtocolsContextFactoryscrapy.core.downloader.contextfactory.load_context_factory_from_settings()scrapy.core.downloader.contextfactory.ScrapyClientContextFactoryscrapy.core.downloader.tls.ScrapyClientTLSOptions
Passing
strinstead ofbytestoscrapy.utils.sitemap.Sitemapandscrapy.utils.sitemap.sitemap_urls_from_robots()is deprecated. (#7007)scrapy.utils.misc.walk_modules()is deprecated. You can usescrapy.utils.misc.walk_modules_iter()instead. (#7388)scrapy.shell.Shell.inthreadis deprecated. You can usescrapy.shell.Shell.fetch_availableinstead to check iffetch()can be used. (#7395)scrapy.commands.ScrapyCommand.set_crawler()is deprecated. (#7276)
New features
Added an experimental mode for running Scrapy without installing a Twisted reactor: set
TWISTED_REACTOR_ENABLEDtoFalseto enable it. This mode has limitations, refer to its documentation for details. As long as it’s experimental, its behavior and related features and APIs may change in future Scrapy releases in a breaking way. (#6219, #7185, #7186, #7187, #7188, #7190, #7197, #7199, #7209, #7228, #7355, #7366, #7385, #7395)Added the
scrapy.utils.reactorless.is_reactorless()function that checks if there is a running asyncio event loop but no Twisted reactor. (#7185, #7199)Changed
scrapy.utils.asyncio.is_asyncio_available()to returnTrueif there is a running asyncio loop, even if no Twisted reactor is installed. (#7185, #7199)Added an experimental download handler that uses the httpx library and doesn’t require a Twisted reactor:
HttpxDownloadHandler. As long as it’s experimental, its behavior may change in future Scrapy releases in a breaking way. (#6805, #7239, #7368, #7384)Added the
DOWNLOAD_BIND_ADDRESSsetting as a global counterpart to the per-requestbindaddressmeta key. (#7266, #7283)Added the
DOWNLOAD_VERIFY_CERTIFICATESsetting that can be set toTrueto make Scrapy abort HTTPS requests when the server certificate is invalid or doesn’t match the domain. (#7379)The built-in HTTP download handlers now raise Scrapy-specific exceptions instead of implementation-specific ones, to allow unified handling of similar problems caused by different implementations. The default value of the
RETRY_EXCEPTIONSsetting was updated replacing Twisted-specific exceptions with these new ones. The exceptions:(#7208)
Added the
memusage_warning_reachedsignal emitted by theMemoryUsageextension when the memory usage reachesMEMUSAGE_WARNING_MB. (#7249, #7263)Added
Headers.to_tuple_list()that returns headers as a list of(key, value)tuples. (#7239)S3DownloadHandlernow uses the download handler configured for the"https"scheme to make requests instead of always usingHTTP11DownloadHandler. (#7369, #7370)Added
scrapy.utils.misc.walk_modules_iter()as a replacement forscrapy.utils.misc.walk_modules()that returns an iterable instead of a list. (#7388)
Improvements
asyncio.to_thread()is now used instead oftwisted.internet.threads.deferToThread()in the built-in feed storages, media pipeline storages and thescrapy.utils.decorators.inthread()decorator when available. (#7183, #7184, #7349)Improved memory footprint of
RequestandResponseobjects by adding__slots__and omitting empty lists and dicts in some internal attributes. (#7036, #7367, #7374)_ScrapyClientContextFactoryno longer mutates the SSL context, to avoid the behavior that was deprecated in pyOpenSSL 25.1.0. (#6859, #7353)Improved memory usage of
SitemapSpiderandscrapy.utils.sitemap.Sitemap. (#3529, #7007)Improved the scheduling behavior of
DownloaderAwarePriorityQueuewhen crawling multiple domains. (#7293, #7351)HTTP11DownloadHandlerandH2DownloadHandlernow handle TLS verbose logging (seeDOWNLOADER_CLIENT_TLS_VERBOSE_LOGGING) directly instead of relying on_ScrapyClientContextFactory. (#7387)The server certificate verification code now correctly handles certificates with IP addresses in
subjectAltName. (#7353)Improved reliability of
scrapy.utils.trackref.get_oldest(). (#1758, #7375)Other code refactoring and improvements. (#7210, #7238, #7376, #7386, #7395, #7405, #7410)
Bug fixes
Media pipelines should now wait for uploads to asynchronous storages (e.g.
S3FilesStore) to complete. (#2183, #6369, #7182)Fixed merging
*_BASEsettings (e.g. mergingDOWNLOADER_MIDDLEWARESwithDOWNLOADER_MIDDLEWARES_BASE) when a component is referred to by a class object in one setting and by a string import path in the other one. (#6912, #6993)scrapy runspiderandscrapy crawlnow set the exit code to 1 if an exception happened early (this was broken since Scrapy 2.13.0). (#6820, #7255)Fixed repeated warnings about data loss (see
DOWNLOAD_FAIL_ON_DATALOSS) not being suppressed inHTTP11DownloadHandler. (#7222)Improved FTP connection management in
scrapy.pipelines.files.FTPFilesStore. (#7256)Fixed the
spidervariable in the shell, which wasn’t available since Scrapy 2.13.0. (#7395)
Documentation
The
llms.txtandllms-full.txtfiles and Markdown versions of pages are now generated when the HTML documentation is built. (#7380)Added a “Copy as Markdown” button to the HTML documentation. (#7380)
Added docs for using Pydantic models as items. (#6955, #6966)
Documented job directory contents. (#4842, #5260)
Improved docs for
dont_filter. (#6398, #7245)Clarified that settings related to
TWISTED_DNS_RESOLVERare only taken into account if the selected resolver supports them. (#7385)Other documentation improvements and fixes. (#7248, #7274, #7406, #7408)
Quality assurance
Added the
no-reactortest environment that doesn’t install a Twisted reactor and usespytest-asyncioinstead ofpytest-twistedto run asynchronous test functions. (#6952, #7189, #7233, #7234, #7254, #7259)CI and test improvements and fixes. (#7060, #7223, #7232, #7241, #7250, #7256, #7276, #7277, #7279, #7329, #7363, #7381, #7402)
Scrapy 2.14.2 (2026-03-12)
Security bug fixes
Values from the
Referrer-Policyheader of HTTP responses are no longer executed as Python callables. See the cwxj-rr6w-m6w7 security advisory for details.In line with the standard, 301 redirects of
POSTrequests are converted intoGETrequests.Converting to a
GETrequest implies not only a method change, but also omitting the body andContent-*headers in the redirect request. On cross-origin redirects (for example, cross-domain redirects), this is effectively a security bug fix for scenarios where the body contains secrets.
Deprecations
Passing a response URL string as the first positional argument to
scrapy.spidermiddlewares.referer.RefererMiddleware.policy()is deprecated. Pass aResponseinstead.The parameter has also been renamed to
responseto reflect this change. The old parameter name (resp_or_url) is deprecated.
New features
Added a new setting,
REFERRER_POLICIES, to allow customizing supported referrer policies.
Bug fixes
Made additional redirect scenarios convert to
GETin line with the standard:Only
POST302 redirects are converted intoGETrequests; other methods are preserved.HEAD303 redirects are not converted intoGETrequests.GET303 redirects do not have their body or standardContent-*headers removed.
Redirects where the original request body is dropped now also have their
Content-Encoding,Content-LanguageandContent-Locationheaders removed, in addition to theContent-TypeandContent-Lengthheaders that were already being removed.Redirects now preserve the source URL fragment if the redirect URL does not include one. This is useful when using browser-based download handlers, such as scrapy-playwright or scrapy-zyte-api, while letting Scrapy handle redirects.
The
Refererheader is now removed on redirect ifRefererMiddlewareis disabled.The handling of the
Refererheader on redirects now takes into account theReferer-Policyheader of the response that triggers the redirect.
Scrapy 2.14.1 (2026-01-12)
Deprecations
scrapy.utils.defer.maybeDeferred_coro()is deprecated. (#7212)
Bug fixes
Fixed custom stats collectors that require a
spiderargument in theiropen_spider()andclose_spider()methods not receiving the argument when called by the engine.Note, however, that the
spiderargument is now deprecated and will stop being passed in a future version of Scrapy.(#7213)
Quality assurance
Scrapy 2.14.0 (2026-01-05)
Highlights:
More coroutine-based replacements for Deferred-based APIs
The default priority queue is now
DownloaderAwarePriorityQueueDropped support for Python 3.9 and PyPy 3.10
Improved and documented the API for custom download handlers
Modified requirements
Backward-incompatible changes
If you set the
TWISTED_REACTORsetting to a non-asyncio value at the spider level, you may now need to set theFORCE_CRAWLER_PROCESSsetting toTruewhen running Scrapy via its command-line tool to avoid a reactor mismatch exception. (#6845)The
log_count/*stats no longer count some of the early messages that they counted before. While the earliest log messages, emitted before the counter is initialized, were never counted, the counter initialization now happens later than in previous Scrapy versions. You may need to adjust expected values if you retrieve and compare values of these stats in your code. (#7046)The classes listed below are now abstract base classes. They cannot be instantiated directly and their subclasses need to override the abstract methods listed below to be able to be instantiated. If you previously instantiated these classes directly, you will now need to subclass them and provide trivial (e.g. empty) implementations for the abstract methods.
-
scrapy.exporters.BaseItemExporterscrapy.extensions.feedexport.BlockingFeedStoragescrapy.middleware.MiddlewareManager_get_mwlist_from_settings()
scrapy.spidermiddlewares.referer.ReferrerPolicyreferrer()
(#6930)
-
Scrapy no longer passes a
spiderargument to any methods of thestats collector. It wasn’t passed in many of the calls even in older Scrapy versions, so we don’t expect existing custom stats collector implementations to require aspiderargument. If your implementation needs aSpiderinstance, you can get it from theCrawlerinstance passed to the constructor. (#7011)scrapy.middleware.MiddlewareManagerno longer includes code for handlingopen_spider()andclose_spider()component methods. As this code was only used for pipelines it was moved intoscrapy.pipelines.ItemPipelineManager. This change should only affect custom subclasses ofMiddlewareManager. The following code was moved:scrapy.middleware.MiddlewareManager.open_spider()scrapy.middleware.MiddlewareManager.close_spider()Code in
scrapy.middleware.MiddlewareManager._add_middleware()that processesopen_spider()andclose_spider()component methods.
(#7006)
scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware.process_request()now returns a coroutine, previously it returned aDeferredobject orNone. Therobot_parser()method was also changed to return a coroutine. This change only impacts code that subclassesRobotsTxtMiddlewareor calls its methods directly. (#6802)The built-in download handlers have been refactored, changing the signatures of their methods. This change should only affect user code that subclasses any of these handlers or calls their methods directly. (#6778, #7164)
scrapy.pipelines.media.MediaPipeline.process_item()now returns a coroutine, previously it returned aDeferredobject. This change only impacts code that calls this method directly. (#7177)
Deprecation removals
The
from_settings()method of the following components, deprecated in Scrapy 2.12.0, is removed. You should usefrom_crawler()instead.scrapy.mail.MailSenderscrapy.middleware.MiddlewareManagerscrapy.core.downloader.contextfactory.ScrapyClientContextFactory
(#7126)
Scrapy no longer calls
from_settings()methods of 3rd-party components, deprecated in Scrapy 2.12.0. You should define afrom_crawler()method instead. (#7126)The initialization flow of
scrapy.pipelines.media.MediaPipelineand its subclasses was simplified, it now mandatesfrom_crawler()methods andcrawlerarguments of__init__()methods. Not using these was deprecated in Scrapy 2.12.0. (#7126)The
REQUEST_FINGERPRINTER_IMPLEMENTATIONsetting, deprecated in Scrapy 2.12.0, is removed. (#7126)The
scrapy.utils.misc.create_instance()function, deprecated in Scrapy 2.12.0, is removed. Usescrapy.utils.misc.build_from_crawler()instead. (#7126)The
scrapy.core.downloader.Downloader._get_slot_key()function, deprecated in Scrapy 2.12.0, is removed. Usescrapy.core.downloader.Downloader.get_slot_key()instead. (#7126)The
scrapy.twisted_versionattribute, deprecated in Scrapy 2.12.0, is removed. You should instead use thetwisted.versionattribute directly. (#7126)The following utility functions, deprecated in Scrapy 2.12.0, are removed:
scrapy.utils.defer.process_chain_both()scrapy.utils.python.equal_attributes()scrapy.utils.python.flatten()scrapy.utils.python.iflatten()scrapy.utils.request.request_authenticate()scrapy.utils.test.assert_samelines()
(#7126)
scrapy.utils.serialize.ScrapyJSONDecoder, deprecated in Scrapy 2.12.0, is removed. (#7126)The
scrapy.extensions.feedexport.build_storage()function, deprecated in Scrapy 2.12.0, is removed, you can instead call the builder callable directly. (#7126)scrapy.spidermiddlewares.offsite.OffsiteMiddleware, deprecated in Scrapy 2.11.2, is removed.scrapy.downloadermiddlewares.offsite.OffsiteMiddlewareshould be used instead. (#6926)
Deprecations
The following methods that return a
Deferredare deprecated in favor of their coroutine-based replacements:scrapy.core.downloader.handlers.DownloadHandlersdownload_request()(usedownload_request_async())
scrapy.core.downloader.middleware.DownloaderMiddlewareManagerdownload()(usedownload_async())
scrapy.core.engine.ExecutionEnginestart()(usestart_async())stop()(usestop_async())close()(useclose_async())open_spider()(useopen_spider_async())close_spider()(useclose_spider_async())download()(usedownload_async())
scrapy.core.scraper.Scraperopen_spider()(useopen_spider_async())call_spider()(usecall_spider_async())close_spider()(useclose_spider_async())handle_spider_output()(usehandle_spider_output_async())start_itemproc()(usestart_itemproc_async())
scrapy.core.spidermw.SpiderMiddlewareManagerscrape_response()(usescrape_response_async())
-
stop()(usestop_async())
scrapy.pipelines.ItemPipelineManagerprocess_item()(useprocess_item_async())open_spider()(useopen_spider_async())close_spider()(useclose_spider_async())
scrapy.signalmanager.SignalManagersend_catch_log_deferred()(usesend_catch_log_async())
scrapy.utils.signal.send_catch_log_deferred()(usescrapy.utils.signal.send_catch_log_async())
(#6791, #6842, #6979, #6997, #6999, #7005, #7043, #7069, #7161, #7164)
The following spider attributes are deprecated in favor of settings:
download_maxsize(useDOWNLOAD_MAXSIZE)download_timeout(useDOWNLOAD_TIMEOUT)download_warnsize(useDOWNLOAD_WARNSIZE)max_concurrent_requests(useCONCURRENT_REQUESTS_PER_DOMAIN)user_agent(useUSER_AGENT)
Returning a
Deferredfrom the following user-defined functions is deprecated in favor of defining them as coroutine functions:spider callbacks and errbacks (which was never officially supported and may work incorrectly)
the
process_request(),process_response()andprocess_exception()methods of custom downloader middlewaresthe
process_item(),open_spider()andclose_spider()methods of custom pipelinessignal handlers
the
download_request()andclose()methods of custom download handlers
(#6718, #6778, #7069, #7147, #7148, #7149, #7150, #7151, #7161, #7164, #7179)
Passing a
spiderargument to the following methods is deprecated:scrapy.core.spidermw.SpiderMiddlewareManager.process_start()scrapy.core.downloader.Downloader.fetch()scrapy.core.downloader.Downloader._get_slot()scrapy.core.downloader.handlers.DownloadHandlers.download_request()all public methods of
scrapy.statscollectors.StatsCollectorscrapy.spidermiddlewares.base.BaseSpiderMiddleware.process_spider_output()scrapy.spidermiddlewares.base.BaseSpiderMiddleware.process_spider_output_async()all
process_*()methods of built-in downloader middlewaresall
process_*()methods of built-in spider middlewaresscrapy.pipelines.media.MediaPipeline.open_spider()scrapy.pipelines.media.MediaPipeline.process_item()
(#6750, #6927, #6984, #7006, #7011, #7033, #7037, #7045, #7178)
Instantiating subclasses of
scrapy.middleware.MiddlewareManagerwithout aCrawlerinstance is deprecated. (#6984)For the following user-defined functions and methods requiring a
spiderargument is deprecated, if you need aSpiderinstance inside them you should get it from theCrawlerinstance (you may need to refactor your code to save that instance in e.g. thefrom_crawler()method):the
process_request(),process_response()andprocess_exception()methods of custom downloader middlewaresthe
process_spider_input(),process_spider_output(),process_spider_output_async()andprocess_spider_exception()methods of custom spider middlewaresthe
process_item()method of custom pipelinesthe
fetch()method of a customDOWNLOADER
The following things in custom download handlers are deprecated:
not having a
lazyattribute (you should define it asTrueif you want to keep the current behavior)returning a
Deferredfrom thedownload_request()method (you should refactor it to return a coroutine; you also need to remove thespiderargument when doing this)not having a
close()method, having a synchronous one or one that returns aDeferred(you should refactor it to return a coroutine or add an empty one if you don’t have it)
Custom implementations of
ITEM_PROCESSORshould now defineprocess_item_async(),open_spider_async()andclose_spider_async()methods instead of, or in addition to,process_item(),open_spider()andclose_spider(). (#7005, #7043)The
CONCURRENT_REQUESTS_PER_IPsetting is deprecated, useCONCURRENT_REQUESTS_PER_DOMAINinstead. (#6917, #6921)The
scrapy.core.downloader.handlers.httpmodule is deprecated. You should importscrapy.core.downloader.handlers.http11.HTTP11DownloadHandlerdirectly instead of importing thescrapy.core.downloader.handlers.http.HTTPDownloadHandleralias. (#7079)The
scrapy.utils.decorators.defers()decorator is deprecated, you can usetwisted.internet.defer.maybeDeferred()directly or reimplement this decorator in your code. (#7164)scrapy.spiders.CrawlSpider._parse_response()is deprecated, usescrapy.spiders.CrawlSpider.parse_with_rules()instead. (#4463, #6804)The functions that add a delay to a Deferred are deprecated, their underlying Twisted functions can be used instead, either directly if a delay isn’t needed, or with some explicit way to add a delay if it’s needed:
scrapy.utils.defer.mustbe_deferred()(you can usetwisted.internet.defer.maybeDeferred())scrapy.utils.defer.defer_succeed()(you can usetwisted.internet.defer.succeed())scrapy.utils.defer.defer_fail()(you can usetwisted.internet.defer.fail())scrapy.utils.defer.defer_result()(you can usetwisted.internet.defer.succeed()andtwisted.internet.defer.fail())
(#6937)
New features
Added
scrapy.crawler.AsyncCrawlerProcessandscrapy.crawler.AsyncCrawlerRunneras counterparts toCrawlerProcessandCrawlerRunnerthat offer coroutine-based APIs. (#6789, #6790, #6796, #6817, #6845, #7034)Added coroutine counterparts to some of the Deferred-based APIs:
scrapy.core.downloader.handlers.DownloadHandlersdownload_request_async()(todownload_request())
scrapy.core.downloader.middleware.DownloaderMiddlewareManagerdownload_async()(todownload())
scrapy.core.engine.ExecutionEnginestart_async()(tostart())stop_async()(tostop())close_async()(toclose())open_spider_async()(toopen_spider())close_spider_async()(toclose_spider())download_async()(todownload())
scrapy.core.scraper.Scraperopen_spider_async()(toopen_spider())close_spider_async()(toclose_spider())start_itemproc_async()(tostart_itemproc())
-
crawl_async()(tocrawl())stop_async()(tostop())
scrapy.pipelines.ItemPipelineManagerprocess_item_async()(toprocess_item())open_spider_async()(toopen_spider())close_spider_async()(toclose_spider())
scrapy.signalmanager.SignalManagersend_catch_log_async()(tosend_catch_log_deferred())
(#6781, #6791, #6792, #6795, #6801, #6817, #6842, #6997, #7005, #7043, #7069,:gh:7164, #7202)
The default value of the
SCHEDULER_PRIORITY_QUEUEsetting is now'scrapy.pqueues.DownloaderAwarePriorityQueue'. (#6924, #6940)Added
scrapy.extensions.logcount.LogCount, an enabled-by-default extension that is responsible for thelog_count/*stats. Previously, this code was inscrapy.crawler.Crawlerand couldn’t be disabled. (#7046)Added
scrapy.spiders.CrawlSpider.parse_with_rules()as a public replacement for_parse_response(). (#4463, #6804)Added
scrapy.utils.asyncio.is_asyncio_available()as an alternative toscrapy.utils.reactor.is_asyncio_reactor_installedwith a future-proof name and semantics. (#6827)The API for download handlers, previously undocumented, has been modernized and documented. An optional base class,
scrapy.core.downloader.handlers.base.BaseDownloadHandler, has been added to simplify writing custom download handlers that conform to the current API. (#4944, #6778, #7164)Added
scrapy.utils.defer.ensure_awaitable(), which can be helpful to call user-defined functions that can return coroutines, Deferreds or values directly. (#7005)The
requests.seenfile, written byRFPDupeFilterwhen job persistence is enabled, now uses line buffering to reduce data loss in spider crashes. (#6019, #7094)Images downloaded by
ImagesPipelineare now automatically transposed based on EXIF data. (#6525, #6975)
Improvements
Bug fixes
Setting
FILES_STOREorIMAGES_STOREtoNonenow correctly disables the respective pipeline. (#6964, #6969)MetaRefreshMiddlewarenow uses the URL set in the<base>tag as the base URL when redirecting to a relative URL. (#7042, #7047)Passing
Noneas a value of thedownload_slotrequest meta key is now handled in the same way as not setting this meta key at all. (#7172)Fixed parsing of the first line of
robots.txtfiles that have a BOM. (#6195, #7095)
Documentation
Added documentation about download handlers, their API and built-in handlers. (#4944, #7164)
Added a section about the scrapy-spider-metadata library to the spider argument docs. (#6676, #6957, #7116)
Improved the docs about coroutine-based and Deferred-based APIs. (#6800, #7146)
Other documentation improvements and fixes. (#7058, #7076, #7109, #7195, #7198)
Quality assurance
Switched from
twisted.trialtopytest-twistedand replaced remainingunittestandtwisted.trialfeatures withpytestones. (#6658, #6873, #6884, #6938)Enabled fancy
pytestasserts. (#6888)Added Sphinx Lint to the
pre-commitconfiguration. (#6920)CI and test improvements and fixes. (#6649, #6769, #6821, #6835, #6836, #6846, #6883, #6885, #6889, #6905, #6928, #6933, #6941, #6942, #6945, #6947, #6960, #6968, #6972, #6974, #6996, #7003, #7012, #7013, #7050, #7059, #7070, #7073, #7118, #7127, #7141, #7143, #7145, #7173)
Code cleanups. (#6803, #6838, #6849, #6875, #6876, #6892, #6930, #6949, #6970, #6977, #6986, #7008, #7177)