Core API
This section documents the Scrapy core API, and it’s intended for developers of extensions and middlewares.
Crawler API
The main entry point to the Scrapy API is the Crawler
object, which components can get for
initialization. It provides access to all Scrapy core
components, and it is the only way for components to access them and hook their
functionality into Scrapy.
The Extension Manager is responsible for loading and keeping track of installed
extensions, and it’s configured through the EXTENSIONS setting,
which contains a dictionary of all available extensions and their order similar
to how you configure the downloader middlewares.
- class scrapy.crawler.Crawler(spidercls: type[Spider], settings: dict[str, Any] | Settings | None = None, init_reactor: bool = False)[source]
The Crawler object must be instantiated with a
scrapy.Spidersubclass and ascrapy.settings.Settingsobject.The
engine,extensions,logformatter,request_fingerprinterandstatsattributes get their value when the crawl starts, and raiseRuntimeErrorwhen read before that.Changed in version 2.18.0: Those attributes used to be
Nonebefore getting their value.- request_fingerprinter
The request fingerprint builder of this crawler.
This is used from extensions and middlewares to build short, unique identifiers for requests. See Request fingerprints.
- settings
The settings manager of this crawler.
This is used by extensions & middlewares to access the Scrapy settings of this crawler.
For an introduction on Scrapy settings see Settings.
For the API see
Settingsclass.
- signals
The signals manager of this crawler.
This is used by extensions & middlewares to hook themselves into Scrapy functionality.
For an introduction on signals see Signals.
For the API see
SignalManagerclass.
- stats
The stats collector of this crawler.
This is used from extensions & middlewares to record stats of their behaviour, or access stats collected by other extensions.
For an introduction on stats collection see Stats Collection.
For the API see
StatsCollectorclass.
- logformatter: _LateAttribute[LogFormatter]
The log formatter of this crawler.
This is used from extensions & middlewares to build the messages that they log about crawling events.
For the API see the
LogFormatterclass.
- extensions
The extension manager that keeps track of enabled extensions.
Most extensions won’t need to access this attribute.
For an introduction on extensions and a list of available extensions on Scrapy see Extensions.
- engine: _LateAttribute[ExecutionEngine]
The execution engine, which coordinates the core crawling logic between the scheduler, downloader and spiders.
Some extensions may want to access the Scrapy engine to inspect or modify the downloader and scheduler behaviour, although this is an advanced use and this API is not yet stable.
- spider
Spider currently being crawled. This is an instance of the spider class provided while constructing the crawler, and it is created after the arguments given in the
crawl()method.
- async crawl_async(*args: Any, **kwargs: Any) None[source]
Start the crawler by instantiating its spider class with the given args and kwargs arguments, while setting the execution engine in motion. Should be called only once.
Added in version 2.14.
Complete when the crawl is finished.
- crawl(*args: Any, **kwargs: Any) Generator[Deferred[Any], Any, None][source]
Start the crawler by instantiating its spider class with the given args and kwargs arguments, while setting the execution engine in motion. Should be called only once.
Return a deferred that is fired when the crawl is finished.
- async stop_async(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') None[source]
Stop the crawler.
Added in version 2.14.
Changed in version 2.20.0: Calling it while the spider is being opened now closes the spider as soon as it is open.
Completes when the crawl has finished, except when the spider is still being opened or the crawler is already stopping, in which case it completes immediately, and when
engine_startedhandlers are still running, in which case it completes once the spider is closed.
- stop(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') Deferred[None][source]
Stop the crawler.
- get_addon(cls: type[_T]) _T | None[source]
Return the run-time instance of an add-on of the specified class or a subclass, or
Noneif none is found.Added in version 2.12.
- get_downloader_middleware(cls: type[_T]) _T | None[source]
Return the run-time instance of a downloader middleware of the specified class or a subclass, or
Noneif none is found.Added in version 2.12.
This method can only be called after the crawl engine has been created, e.g. at signals
engine_startedorspider_opened.
- get_extension(cls: type[_T]) _T | None[source]
Return the run-time instance of an extension of the specified class or a subclass, or
Noneif none is found.Added in version 2.12.
This method can only be called after the extension manager has been created, e.g. at signals
engine_startedorspider_opened.
- get_item_pipeline(cls: type[_T]) _T | None[source]
Return the run-time instance of a item pipeline of the specified class or a subclass, or
Noneif none is found.Added in version 2.12.
This method can only be called after the crawl engine has been created, e.g. at signals
engine_startedorspider_opened.
- get_spider_middleware(cls: type[_T]) _T | None[source]
Return the run-time instance of a spider middleware of the specified class or a subclass, or
Noneif none is found.Added in version 2.12.
This method can only be called after the crawl engine has been created, e.g. at signals
engine_startedorspider_opened.
- class scrapy.crawler.AsyncCrawlerRunner(settings: dict[str, Any] | Settings | None = None)[source]
This is a convenient helper class that keeps track of, manages and runs crawlers inside an already setup
reactoror asyncio event loop.The AsyncCrawlerRunner object must be instantiated with a
Settingsobject.When the
TWISTED_REACTOR_ENABLEDsetting is set toTrue, this class requires a reactor to be installed and uses it, otherwise it requires a reactor to not be installed but requires a running asyncio event loop and uses it.This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See Run Scrapy from a script for an example.
This class provides coroutine APIs. It requires
AsyncioSelectorReactorwhen used with a reactor.- crawl(crawler_or_spidercls: type[Spider] | str | Crawler, *args: Any, **kwargs: Any) Task[None][source]
Run a crawler with the provided arguments.
It will call the given Crawler’s
crawl_async()method, while keeping track of it so it can be stopped later.If
crawler_or_spiderclsisn’t aCrawlerinstance, this method will try to create one using this parameter as the spider class given to it.Returns a
Taskobject which completes when the crawling is finished.
- async stop(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') None[source]
Stops simultaneously all the crawling jobs taking place.
Completes when all their
Crawler.stop_async()calls have completed.
- class scrapy.crawler.CrawlerRunner(settings: dict[str, Any] | Settings | None = None)[source]
This is a convenient helper class that keeps track of, manages and runs crawlers inside an already setup
reactor.The CrawlerRunner object must be instantiated with a
Settingsobject.This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See Run Scrapy from a script for an example.
This class provides Deferred-based APIs. Use
AsyncCrawlerRunnerfor modern coroutine APIs.- crawl(crawler_or_spidercls: type[Spider] | str | Crawler, *args: Any, **kwargs: Any) Deferred[None][source]
Run a crawler with the provided arguments.
It will call the given Crawler’s
crawl()method, while keeping track of it so it can be stopped later.If
crawler_or_spiderclsisn’t aCrawlerinstance, this method will try to create one using this parameter as the spider class given to it.Returns a deferred that is fired when the crawling is finished.
- class scrapy.crawler.AsyncCrawlerProcess(settings: dict[str, Any] | Settings | None = None, install_root_handler: bool | None = None)[source]
Bases:
CrawlerProcessBase,AsyncCrawlerRunnerA class to run multiple scrapy crawlers in a process simultaneously.
This class extends
AsyncCrawlerRunnerby adding support for starting areactorand handling shutdown signals, like the keyboard interrupt command Ctrl-C. It also configures top-level logging.This utility should be a better fit than
AsyncCrawlerRunnerif you aren’t running anotherreactorwithin your application.The AsyncCrawlerProcess object must be instantiated with a
Settingsobject.When the
TWISTED_REACTOR_ENABLEDsetting is set toTrue, this class installs a reactor and uses it, otherwise it requires a reactor to not be installed but installs an asyncio event loop and uses it.- Parameters:
install_root_handler – whether to install root logging handler (default: the
LOG_INSTALL_ROOT_HANDLERsetting)
This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See Run Scrapy from a script for an example.
This class provides coroutine APIs. It requires
AsyncioSelectorReactorwhen used with a reactor.- start(stop_after_crawl: bool = True, install_signal_handlers: bool = True) None[source]
This method starts a
reactoror an asyncio event loop, depending on the value of theTWISTED_REACTOR_ENABLEDsetting.When using a reactor it adjusts its pool size to
REACTOR_THREADPOOL_MAXSIZEand installs a DNS resolver based onTWISTED_DNS_RESOLVER.If
stop_after_crawlis True, the reactor/event loop will be stopped after all crawlers have finished, usingjoin().
- crawl(crawler_or_spidercls: type[Spider] | str | Crawler, *args: Any, **kwargs: Any) Task[None]
Run a crawler with the provided arguments.
It will call the given Crawler’s
crawl_async()method, while keeping track of it so it can be stopped later.If
crawler_or_spiderclsisn’t aCrawlerinstance, this method will try to create one using this parameter as the spider class given to it.Returns a
Taskobject which completes when the crawling is finished.
- create_crawler(crawler_or_spidercls: type[Spider] | str | Crawler) Crawler
Return a
Crawlerobject.If
crawler_or_spiderclsis a Crawler, the runner’s settings are merged into it as defaults: for each setting, the runner’s value is applied only if the Crawler does not already have that setting at an equal or higher priority. The Crawler is then returned.If
crawler_or_spiderclsis a Spider subclass, a new Crawler is constructed for it using this runner’s settings.If
crawler_or_spiderclsis a string, this function finds a spider with this name in a Scrapy project (using spider loader), then creates a Crawler instance for it.
- async stop(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') None
Stops simultaneously all the crawling jobs taking place.
Completes when all their
Crawler.stop_async()calls have completed.
- class scrapy.crawler.CrawlerProcess(settings: dict[str, Any] | Settings | None = None, install_root_handler: bool | None = None)[source]
Bases:
CrawlerProcessBase,CrawlerRunnerA class to run multiple scrapy crawlers in a process simultaneously.
This class extends
CrawlerRunnerby adding support for starting areactorand handling shutdown signals, like the keyboard interrupt command Ctrl-C. It also configures top-level logging.This utility should be a better fit than
CrawlerRunnerif you aren’t running anotherreactorwithin your application.The CrawlerProcess object must be instantiated with a
Settingsobject.- Parameters:
install_root_handler – whether to install root logging handler (default: the
LOG_INSTALL_ROOT_HANDLERsetting)
This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See Run Scrapy from a script for an example.
This class provides Deferred-based APIs. Use
AsyncCrawlerProcessfor modern coroutine APIs.- start(stop_after_crawl: bool = True, install_signal_handlers: bool = True) None[source]
This method starts a
reactor, adjusts its pool size toREACTOR_THREADPOOL_MAXSIZE, and installs a DNS resolver based onTWISTED_DNS_RESOLVER.If
stop_after_crawlis True, the reactor will be stopped after all crawlers have finished, usingjoin().
- crawl(crawler_or_spidercls: type[Spider] | str | Crawler, *args: Any, **kwargs: Any) Deferred[None]
Run a crawler with the provided arguments.
It will call the given Crawler’s
crawl()method, while keeping track of it so it can be stopped later.If
crawler_or_spiderclsisn’t aCrawlerinstance, this method will try to create one using this parameter as the spider class given to it.Returns a deferred that is fired when the crawling is finished.
- create_crawler(crawler_or_spidercls: type[Spider] | str | Crawler) Crawler
Return a
Crawlerobject.If
crawler_or_spiderclsis a Crawler, the runner’s settings are merged into it as defaults: for each setting, the runner’s value is applied only if the Crawler does not already have that setting at an equal or higher priority. The Crawler is then returned.If
crawler_or_spiderclsis a Spider subclass, a new Crawler is constructed for it using this runner’s settings.If
crawler_or_spiderclsis a string, this function finds a spider with this name in a Scrapy project (using spider loader), then creates a Crawler instance for it.
- stop(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') Deferred[Any]
Stops simultaneously all the crawling jobs taking place.
Returns a deferred that is fired when all their
Crawler.stop_async()calls have completed.
Settings API
- scrapy.settings.SETTINGS_PRIORITIES
Dictionary that sets the key name and priority level of the default settings priorities used in Scrapy.
Each item defines a settings entry point, giving it a code name for identification and an integer priority. Greater priorities take more precedence over lesser ones when setting and retrieving values in the
Settingsclass.SETTINGS_PRIORITIES = { "default": 0, "command": 10, "addon": 15, "project": 20, "spider": 30, "cmdline": 40, }
For a detailed explanation on each settings sources, see: Settings.
- scrapy.settings.get_settings_priority(priority: int | str) int[source]
Small helper function that looks up a given string priority in the
SETTINGS_PRIORITIESdictionary and returns its numerical value, or directly returns a given numerical priority.
- scrapy.utils.project.get_project_settings() Settings[source]
Return a
Settingsobject with the project settings of the current project.Settings from sources with a higher precedence, such as spider settings, are applied when a crawl starts.
- class scrapy.settings.Settings(values: _SettingsInput = None, priority: int | str = 'project')[source]
Bases:
BaseSettingsThis object stores Scrapy settings for the configuration of internal components, and can be used for any further customization.
It is a direct subclass and supports all methods of
BaseSettings. Additionally, after instantiation of this class, the new object will have the global default settings described on Built-in settings reference already populated.
- class scrapy.settings.BaseSettings(values: _SettingsInput = None, priority: int | str = 'project')[source]
Instances of this class behave like dictionaries, but store priorities along with their
(key, value)pairs, and can be frozen (i.e. marked immutable).Key-value entries can be passed on initialization with the
valuesargument, and they would take theprioritylevel (unlessvaluesis already an instance ofBaseSettings, in which case the existing priority levels will be kept). If thepriorityargument is a string, the priority name will be looked up inSETTINGS_PRIORITIES. Otherwise, a specific integer should be provided.Once the object is created, new settings can be loaded or updated with the
set()method, and can be accessed with the square bracket notation of dictionaries, or with theget()method of the instance and its value conversion variants. When requesting a stored key, the value with the highest priority will be retrieved.- add_to_list(name: str, item: Any) None[source]
Append item to the
listsetting with the specified name if item is not already in that list.This change is applied regardless of the priority of the name setting. The setting priority is not affected by this change either.
- remove_from_list(name: str, item: Any) None[source]
Remove item from the
listsetting with the specified name.If item is missing, raise
ValueError.This change is applied regardless of the priority of the name setting. The setting priority is not affected by this change either.
- get(name: str, default: Any = None) Any[source]
Get a setting value without affecting its original type.
- getbool(name: str, default: bool = False) bool[source]
Get a setting value as a boolean.
1,'1', True` and'True'returnTrue, while0,'0',False,'False'andNonereturnFalse.For example, settings populated through environment variables set to
'0'will returnFalsewhen using this method.
- getlist(name: str, default: list[Any] | None = None) list[Any][source]
Get a setting value as a list. If the setting original type is a list, a copy of it will be returned. If it’s a string it will be evaluated as a JSON list, or split by “,” as a fallback. If it is an empty string, an empty list will be returned.
For example, settings populated through environment variables set to
'one,two'or'["one", "two"]'will return a list [‘one’, ‘two’] when using this method.
- getdict(name: str, default: dict[Any, Any] | None = None) dict[Any, Any][source]
Get a setting value as a dictionary. If the setting original type is a dictionary, a copy of it will be returned. If it is a string it will be evaluated as a JSON dictionary. In the case that it is a
BaseSettingsinstance itself, it will be converted to a dictionary, containing all its current settings values as they would be returned byget(), and losing all information about priority and mutability.
- getdictorlist(name: str, default: dict[Any, Any] | list[Any] | tuple[Any, ...] | None = None) dict[Any, Any] | list[Any][source]
Get a setting value as either a
dictor alist.If the setting is already a dict or a list, a copy of it will be returned.
If it is a string it will be evaluated as JSON, or as a comma-separated list of strings as a fallback.
For example, settings populated from the command line will return:
{'key1': 'value1', 'key2': 'value2'}if set to'{"key1": "value1", "key2": "value2"}'['one', 'two']if set to'["one", "two"]'or'one,two'
- getwithbase(name: str) BaseSettings[source]
Get a composition of a dictionary-like setting and its
_BASEcounterpart.Use
get_component_priority_dict_with_base()instead if the setting is a component priority dictionary.- Parameters:
name (str) – name of the dictionary-like setting
- get_component_priority_dict_with_base(name: str) BaseSettings[source]
Get a composition of a component priority dictionary setting and its
_BASEcounterpart.Keys are resolved to their import path for deduplication and then restored to their latest input representation.
- Parameters:
name (str) – name of the component priority dictionary setting
- getpriority(name: str) int | None[source]
Return the current numerical priority value of a setting, or
Noneif the givennamedoes not exist.- Parameters:
name (str) – the setting name
- maxpriority() int[source]
Return the numerical value of the highest priority present throughout all settings, or the numerical value for
defaultfromSETTINGS_PRIORITIESif there are no settings stored.
- replace_in_component_priority_dict(name: str, old_cls: type, new_cls: type, priority: int | None = None) None[source]
Replace old_cls with new_cls in the name component priority dictionary.
If old_cls is missing, or has
Noneas value,KeyErroris raised.If old_cls was present as an import string, even more than once, those keys are dropped and replaced by new_cls.
If priority is specified, that is the value assigned to new_cls in the component priority dictionary. Otherwise, the value of old_cls is used. If old_cls was present multiple times (possible with import strings) with different values, the value assigned to new_cls is one of them, with no guarantee about which one it is.
This change is applied regardless of the priority of the name setting. The setting priority is not affected by this change either.
- set(name: str, value: Any, priority: int | str = 'project') None[source]
Store a key/value attribute with a given priority.
Settings should be populated before the Crawler object applies them (in the
crawl_async()orcrawl()method), otherwise they won’t have any effect.- Parameters:
name (str) – the setting name
value (object) – the value to associate with the setting
priority (str or int) – the priority of the setting. Should be a key of
SETTINGS_PRIORITIESor an integer
- set_in_component_priority_dict(name: str, cls: type, priority: int | None) None[source]
Set the cls component in the name component priority dictionary setting with priority.
If cls already exists, its value is updated.
If cls was present as an import string, even more than once, those keys are dropped and replaced by cls.
This change is applied regardless of the priority of the name setting. The setting priority is not affected by this change either.
- setdefault_in_component_priority_dict(name: str, cls: type, priority: int | None) None[source]
Set the cls component in the name component priority dictionary setting with priority if not already defined (even as an import string).
If cls is not already defined, it is set regardless of the priority of the name setting. The setting priority is not affected by this change either.
- setmodule(module: ModuleType | str, priority: int | str = 'project') None[source]
Store settings from a module with a given priority.
This is a helper function that calls
set()for every globally declared uppercase variable ofmodulewith the providedpriority.- Parameters:
module (types.ModuleType or str) – the module or the path of the module
priority (str or int) – the priority of the settings. Should be a key of
SETTINGS_PRIORITIESor an integer
- update(values: _SettingsInput, priority: int | str = 'project') None[source]
Store key/value pairs with a given priority.
This is a helper function that calls
set()for every item ofvalueswith the providedpriority.If
valuesis a string, it is assumed to be JSON-encoded and parsed into a dict withjson.loads()first. If it is aBaseSettingsinstance, the per-key priorities will be used and thepriorityparameter ignored. This allows inserting/updating settings with different priorities with a single command.- Parameters:
values (dict, iterable, string or
BaseSettings) – the settings names and valuespriority (str or int) – the priority of the settings. Should be a key of
SETTINGS_PRIORITIESor an integer
- copy() Self[source]
Make a deep copy of current settings.
This method returns a new instance of this class, populated with the same values and their priorities.
Modifications to the new object won’t be reflected on the original settings.
- freeze() None[source]
Disable further changes to the current settings.
After calling this method, the present state of the settings will become immutable. Trying to change values through the
set()method and its variants won’t be possible and will be alerted.
- copy_to_dict() dict[str, Any][source]
Make a copy of current settings and convert to a dict.
This method returns a new dict populated with the same values as the current settings.
Modifications to the returned dict won’t be reflected on the original settings.
This method can be useful for example for printing settings in Scrapy shell.
SpiderLoader API
Custom spider loaders can be employed by specifying their path in the
SPIDER_LOADER_CLASS project setting. They must implement
SpiderLoaderProtocol.
- class scrapy.spiderloader.SpiderLoaderProtocol(*args, **kwargs)[source]
Protocol for spider loader implementations.
See
SPIDER_LOADER_CLASS.- classmethod from_settings(settings: BaseSettings) Self[source]
Return an instance of the class for the given settings.
- class scrapy.spiderloader.SpiderLoader(settings: BaseSettings)[source]
SpiderLoader is a class which locates and loads spiders in a Scrapy project.
- classmethod from_settings(settings: BaseSettings) Self[source]
Create an instance of the class.
It’s called with the current project settings, and it loads the spiders found recursively in the modules of the
SPIDER_MODULESsetting.
- load(spider_name: str) type[Spider][source]
Return the spider class for the given spider name.
If the spider name is not found, raise a
KeyError.
Signals API
- class scrapy.signalmanager.SignalManager(sender: object = _Anonymous)[source]
- connect(receiver: Callable[..., Any], signal: object, **kwargs: Any) None[source]
Connect a receiver function to a signal.
The signal can be any object, although Scrapy comes with some predefined signals that are documented in the Signals section.
- Parameters:
receiver (collections.abc.Callable) – the function to be connected
signal (object) – the signal to connect to
- disconnect(receiver: Callable[..., Any], signal: object, **kwargs: Any) None[source]
Disconnect a receiver function from a signal. This has the opposite effect of the
connect()method, and the arguments are the same.
- send_catch_log(signal: object, **kwargs: Any) list[tuple[Callable[..., Any], Any]][source]
Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected through the
connect()method).
- send_catch_log_deferred(signal: object, **kwargs: Any) Deferred[list[tuple[Callable[..., Any], Any]]][source]
Like
send_catch_log()but supports asynchronous signal handlers.Returns a Deferred that gets fired once all signal handlers have finished. Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected through the
connect()method).
- async send_catch_log_async(signal: object, **kwargs: Any) list[tuple[Callable[..., Any], Any]][source]
Like
send_catch_log()but supports asynchronous signal handlers.Returns a coroutine that completes once all signal handlers have finished. Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected through the
connect()method).Added in version 2.14.
- disconnect_all(signal: object, **kwargs: Any) None[source]
Disconnect all receivers from the given signal.
- Parameters:
signal (object) – the signal to disconnect from
- async wait_for(signal: object) None[source]
Await the next signal.
See Delaying start request iteration for an example.
Stats Collector API
There are several Stats Collectors available under the
scrapy.statscollectors module and they all implement the Stats
Collector API defined by the StatsCollector
class (which they all inherit from).
Engine API
- class scrapy.core.engine.ExecutionEngine[source]
The execution engine manages all the core components, such as the scheduler, the downloader, or the spider, at run time.
Some components access the engine through
Crawler.engineto access or modify other components, or use core functionality such as closing the running spider.- property scheduler: BaseScheduler | None
The scheduler in use, or
Nonebefore the spider has started.Added in version 2.19.0.
- property state: EngineState
The current lifecycle state of the engine.
Added in version 2.20.0.
- property response_active_size: int
Size, in bytes, that counts toward
RESPONSE_MAX_ACTIVE_SIZE.Added in version 2.20.0.
- property running: bool
Whether the engine is in the
EngineState.RUNNINGstate.Changed in version 2.20.0: Became a read-only property.
- async start_async() None[source]
Start the execution engine.
Added in version 2.14.
Changed in version 2.20.0: In earlier versions, if the spider was not open, it sent the
engine_startedsignal instead of raisingRuntimeError.Completes when the engine is stopped.
Raises
RuntimeErrorif the spider is not open, or if the engine has already been started or stopped.
- async stop_async(*, mode: Literal['graceful', 'fast', 'force'] = 'graceful') None[source]
Stop the execution engine by closing the spider with the
shutdownreason.Added in version 2.14.
Changed in version 2.20.0: This is now a shortcut for
close_spider_async(), see its docs for the behavior in different engine states, including when it completes.
- needs_backout() bool[source]
Returns
Trueif no more requests can be sent at the moment, orFalseotherwise.See Delaying start request iteration for an example.
- async download_async(request: Request) Response[source]
Return a coroutine which fires with a Response as result.
Added in version 2.14.
Only downloader middlewares are applied.
For a request that you build yourself, prefer awaiting it.
- async open_spider_async(*, close_if_idle: bool = True) None[source]
Open the spider.
Added in version 2.14.
Changed in version 2.20.0: In earlier versions, a
CloseSpiderexception raised while the spider was opening was re-raised.Raises
RuntimeErrorif a spider has already been opened.If an exception is raised during opening, the spider is still considered open (the engine always transitions to the
EngineState.SPIDER_OPENstate).If the engine is requested to close the spider during opening, that is done right after the spider is opened.
- async close_spider_async(*, reason: str = 'cancelled', mode: Literal['graceful', 'fast', 'force'] = 'graceful', error: bool = False) None[source]
Stop the crawl with the specified reason and clear all its outstanding requests.
Added in version 2.14.
reason is an arbitrary string; see
finish_reasonfor the reasons that built-in components use. error is a flag that specifies whether the crawl should be considered failed (see thefinish_reason_errorstat). If mode is"graceful", this method will wait until the requests that are already in the downloader are downloaded and processed; if it’s"fast"they will be dropped.If the spider was not opened before, this method raises
RuntimeError.If the spider is still opening, this method completes immediately, and the spider will start closing after it finishes opening, with the reason and error of the first such call.
If the spider is closing or has already been closed, this method completes immediately, ignoring reason and error. If
mode="fast"was passed, it will also drop the requests left in the downloader.Changed in version 2.20.0: Previously, calling it while the spider was closing waited for the in-flight requests to finish, and calling it after the spider had been closed raised
RuntimeError.Otherwise, this method completes after the spider has been closed and the engine has stopped. If
engine_startedhandlers are still running at that point, the engine stops once they finish, and this method completes without waiting for that.
- class scrapy.core.engine.EngineState(*values)[source]
The lifecycle state of
ExecutionEngine.Added in version 2.20.0.
The engine goes through these states in order, possibly skipping some.
- CREATED = 'created'
The engine has been created but no spider has been opened yet.
- SPIDER_OPENING = 'spider_opening'
The spider is being opened. The
spider_openedsignal may be in flight.
- SPIDER_OPEN = 'spider_open'
The spider is open but the engine has not been started yet. Requests can be made via
download_async().
- STARTING = 'starting'
The engine is being started. The
engine_startedsignal may be in flight.
- RUNNING = 'running'
The engine is running. Start requests and requests from callbacks are processed.
- SPIDER_CLOSING = 'spider_closing'
The spider is being closed. The
spider_closedsignal may be in flight. The engine is no longer considered running. Scheduled requests are no longer sent.
- STOPPING = 'stopping'
The spider has been closed. The
engine_startedorengine_stoppedsignal may be in flight.
- STOPPED = 'stopped'
The engine has been stopped and cannot be reused.