Prerequisites
- You’ve read the Getting started page and know how to create and run a basic spider.
- You’re familiar with Fetchers basics and the differences between HTTP, Dynamic, and Stealthy sessions.
What are Sessions?
A session is a pre-configured fetcher instance that stays alive for the duration of the crawl. Instead of creating a new connection or browser for every request, the spider reuses sessions, which is faster and more resource-efficient. By default, every spider creates a single FetcherSession. You can add more sessions or swap the default by overriding theconfigure_sessions() method. You must use the async version of each session only:
Configuring Sessions
Overrideconfigure_sessions() on your spider to set up sessions. The manager parameter is a SessionManager instance — use manager.add() to register sessions:
SessionManager.add() Parameters
Themanager.add() method takes:
Important Notes:
-
If you don’t specify which session to use in requests, the default session is used. The default session is determined in one of two ways:
- The first session you add becomes the default automatically
- The session that gets
default=Truewhen added to the manager
- The session instances you pass don’t have to be already started — the spider checks all sessions and starts them automatically.
-
If you want a specific session to start only when used, use the
lazyargument when adding that session to the manager. Example: start the browser only when you need it, not with the spider start.
SessionManager Implementation
The session management logic is implemented insession.py:
session.py:83-92
session.py:101-130
Multi-Session Spider
Here’s a practical example: use a fast HTTP session for listing pages and a stealth browser for detail pages that have bot protection:sid parameter — it tells the spider which session to use for each request. When you call response.follow() without sid, the session ID from the original request is inherited.
Same Session Class, Different Configurations
Sessions don’t have to be from different classes — you can use the same session class with different configurations:Session Arguments
Extra keyword arguments passed to aRequest (or through response.follow(**kwargs)) are forwarded to the session’s fetch method. This lets you customize individual requests without changing the session configuration:
Browser-Specific Arguments
For browser sessions (AsyncDynamicSession, AsyncStealthySession), you can pass browser-specific arguments like wait_selector, page_action, or extra_headers:
Argument Inheritance
Session Lifecycle
Upon spider closure, the manager automatically checks whether any sessions are still running and closes them before closing the spider.
session.py:94-99