Skip to main content
The 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

Creates an empty session manager. Sessions must be added via the add() method.

Methods

add

Register a session instance.
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).
Returns: self (for chaining) Raises: ValueError if session_id already exists Example:

remove

Remove a session by ID.
str
required
ID of the session to remove.
Raises: KeyError if session_id not found

pop

Remove and return a session.
str
required
ID of the session to remove and return.
Returns: The removed session instance Raises: KeyError if session_id not found Example:

get

Get a session by ID.
str
required
ID of the session to retrieve.
Returns: The session instance Raises: KeyError if session_id not found (with helpful error message listing available sessions) Example:

fetch

Fetch a request using the appropriate session. Automatically starts lazy sessions on first use.
Request
required
The request to fetch.
Returns: Response object with merged metadata from the request Process:
  1. Determine session ID from request (or use default)
  2. Get the session instance
  3. Start lazy session if needed (thread-safe)
  4. Fetch using the session
  5. Merge request.meta into response.meta
  6. Attach request to response.request

start

Start all non-lazy sessions. Called automatically by the async context manager. Example:

close

Close all registered sessions. Called automatically by the async context manager.

Properties

default_session_id

Get the ID of the default session. Returns: Default session ID Raises: RuntimeError if no sessions are registered

session_ids

Get list of all registered session IDs. Returns: List of session ID strings

Special Methods

Async Context Manager

Supports async context manager protocol for automatic start/close. Example:

Contains

Check if a session ID is registered. Example:

Length

Get the number of registered sessions. Example:

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