Skip to main content
The Spider class is an abstract base class for creating web spiders. It provides the core framework for asynchronous web crawling with support for pause/resume, session management, and flexible concurrency control.

Class Definition

Class Attributes

str | None
default:"None"
required
The name of the spider. Must be set in subclasses.
list[str]
default:"[]"
List of URLs where the spider will begin crawling. Used by default start_requests() implementation.
Set[str]
default:"set()"
Set of allowed domains. If set, only requests to these domains will be processed. Supports domain matching (e.g., “example.com” matches “sub.example.com”).

Concurrency Settings

int
default:"4"
Maximum number of concurrent requests globally.
int
default:"0"
Maximum number of concurrent requests per domain. If 0, only global limit applies.
float
default:"0.0"
Delay in seconds between requests to the same domain.
int
default:"3"
Maximum number of retry attempts for blocked requests.

Fingerprint Adjustments

bool
default:"False"
Include session kwargs in request fingerprinting for deduplication.
bool
default:"False"
Keep URL fragments when generating request fingerprints.
bool
default:"False"
Include headers in request fingerprinting.

Logging Settings

int
default:"logging.DEBUG"
Logging level for the spider logger.
str
Log message format. {spider_name} will be replaced with the spider’s name.
str
default:"%Y-%m-%d %H:%M:%S"
Date format for log messages.
str | None
default:"None"
Optional path to a log file. If set, logs will be written to this file.

Constructor

str | Path | AsyncPath | None
default:"None"
Directory for checkpoint files. If provided, enables pause/resume functionality.
float
default:"300.0"
Seconds between periodic checkpoint saves (default 5 minutes).

Abstract Methods

parse

Default callback for processing responses. Must be implemented by subclasses.
Response
required
The response object to parse.
Yields: Dictionary items (scraped data), Request objects (new requests), or None Example:

Methods

start_requests

Generate initial requests to start the crawl. By default, creates Request objects for each URL in start_urls. Override for custom initial request logic. Yields: Request objects Example:

start

Run the spider synchronously and return results. This is the main entry point for running a spider.
bool
default:"False"
Whether to use the faster uvloop/winloop event loop implementation, if available.
Any
Asyncio backend options to pass to anyio.run().
Returns: CrawlResult object containing stats, items, and pause state Example:
Pressing Ctrl+C initiates graceful shutdown. Pressing it again forces immediate stop. If crawldir is set, a checkpoint is saved on graceful shutdown for later resumption.

stream

Stream items as they’re scraped. Ideal for long-running spiders or building applications on top of spiders. Must be called from an async context. Yields: Scraped items (dictionaries) Example:
SIGINT handling for pause/resume is not available in stream mode.

pause

Request graceful shutdown of the crawling process. Active tasks will complete before stopping. Raises: RuntimeError if no active crawl is running

configure_sessions

Configure sessions for this spider. Override this method to add custom sessions. The first session added becomes the default for start_requests() unless specified otherwise.
SessionManager
required
SessionManager instance to configure.
Example:

Hook Methods

These methods can be overridden to customize spider behavior:

on_start

Called before crawling starts. Override for setup logic.
bool
default:"False"
True if the spider is resuming from a checkpoint.

on_close

Called after crawling finishes. Override for cleanup logic.

on_error

Handle request errors for all spider requests. Override for custom error handling.
Request
required
The request that caused the error.
Exception
required
The exception that was raised.

on_scraped_item

Process scraped items before they’re stored. Return None to drop the item silently.
Dict[str, Any]
required
The scraped item to process.
Returns: Processed item or None to drop it Example:

is_blocked

Check if the response is blocked. Override for custom detection logic.
Response
required
The response to check.
Returns: True if blocked, False otherwise Default implementation: Returns True for status codes in {401, 403, 407, 429, 444, 500, 502, 503, 504}

retry_blocked_request

Prepare a blocked request before retrying. Override to modify the request (e.g., rotate proxies, change headers).
Request
required
The request to retry (already copied with incremented retry count).
Response
required
The blocked response.
Returns: Modified request for retry Example:

Properties

stats

Access current crawl statistics. Only available during active crawl (inside stream() iteration). Returns: CrawlStats object Raises: RuntimeError if no active crawl is running

Complete Example

See Also