SessionManager class manages pre-configured session instances for spiders. It allows you to register multiple sessions (FetcherSession, AsyncStealthySession, etc.) and route requests to specific sessions using session IDs.
Class Definition
Constructor
add() method.
Methods
add
str
required
Unique name to reference this session in requests.
Session
required
Pre-configured session instance (FetcherSession, AsyncStealthySession, or AsyncDynamicSession).
bool
default:"False"
If True, this becomes the default session. The first session added is automatically the default.
bool
default:"False"
If True, the session will only be started when a request uses its ID (useful for expensive sessions like browser-based ones).
ValueError if session_id already exists
Example:
remove
str
required
ID of the session to remove.
KeyError if session_id not found
pop
str
required
ID of the session to remove and return.
KeyError if session_id not found
Example:
get
str
required
ID of the session to retrieve.
KeyError if session_id not found (with helpful error message listing available sessions)
Example:
fetch
Request
required
The request to fetch.
- Determine session ID from request (or use default)
- Get the session instance
- Start lazy session if needed (thread-safe)
- Fetch using the session
- Merge request.meta into response.meta
- Attach request to response.request
start
close
Properties
default_session_id
RuntimeError if no sessions are registered
session_ids
Special Methods
Async Context Manager
Contains
Length
Usage Examples
Basic Setup in Spider
Multiple Sessions
Session-Specific Configuration
Dynamic Session Switching
Manual Session Management (Advanced)
Lazy Loading Benefits
Session Types
The manager supports these session types:FetcherSession
AsyncStealthySession
AsyncDynamicSession
Thread Safety
Lazy session initialization is thread-safe via async lock:Error Handling
See Also
- Spider - Using sessions in spiders
- Request - Specifying session IDs in requests
- FetcherSession - HTTP session documentation
- AsyncStealthySession - Stealth browser session