Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/03_concepts/17_proxy_management.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ All our proxy needs are managed by the <ApiLink to="class/ProxyConfiguration">`P

Instead of `proxy_urls`, you can pass a `new_url_function`. It takes no arguments and returns a proxy URL, or `None` to use no proxy. It can be sync or async.

The crawler and the <ApiLink to="class/SessionPool">`SessionPool`</ApiLink> also take another proxy configuration implementation, such as a client of your proxy provider. It needs an async `new_proxy_info()` method, which takes the current proxy of the session or `None`, and returns a `ProxyInfo`, or `None` for no proxy. The pool calls it for every session it creates or restores. Return the saved proxy of a restored session, so that the session keeps its IP address. The persisted state doesn't store proxy passwords, so if the proxy <ApiLink to="class/ProxyInfo#has_redacted_password">`has_redacted_password`</ApiLink>, put the password back into its `url` and `password`, or return another proxy. Otherwise, the pool drops the session.

### Crawler integration

`ProxyConfiguration` integrates seamlessly into <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink> and <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink>.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from contextlib import suppress
from datetime import timedelta

from crawlee import ConcurrencySettings, Request
Expand Down Expand Up @@ -50,9 +51,13 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N
)

async with session_pool:
# The pool creates sessions on demand, so create them before binding
# the first requests to them, for example for authentication
sessions = [await session_pool.get_session() for _ in range(10)]
# Add the sessions before binding the first requests to them,
# for example one session per authenticated profile
profile_ids = [f'profile-{i}' for i in range(10)]
for profile_id in profile_ids:
# A resumed run restores the usable sessions from the persisted state
with suppress(ValueError):
await session_pool.add_session({'id': profile_id})

# Create a pool of requests bound to their respective sessions
# Use `always_enqueue=True` if session initialization happens on a non-unique
Expand All @@ -61,10 +66,10 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N
Request.from_url(
'https://example.org/',
label='session_init',
session_id=session.id,
session_id=profile_id,
use_extended_unique_key=True,
)
for session in sessions
for profile_id in profile_ids
]

await crawler.run(init_requests)
Expand Down
95 changes: 93 additions & 2 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ async def main() -> None:

The `use_session_pool` option is removed from the crawlers. Every crawler processes its requests with sessions from its `SessionPool`, the same as Crawlee JS v4. To configure the pool, pass your own `SessionPool` as `session_pool`.

`context.session` is now a `Session` instead of `Session | None`, so you can drop the `if context.session` checks. A request bound by `session_id` to a session that's no longer usable still fails with a `RequestCollisionError`, now with the message `The Session (id: <id>) bound to the Request is no longer usable`. Its failed request handler gets that session while the pool still holds it, or a retired session with the bound id, instead of `None`.
`context.session` is no longer optional, so you can drop the `if context.session` checks. A request bound by `session_id` to a session that's no longer usable still fails with a `RequestCollisionError`, now with the message `The Session (id: <id>) bound to the Request is no longer usable`. Its failed request handler gets that session while the pool still holds it, or a retired session with the bound id, instead of `None`.

Without the session pool, a 401, 403 or 429 response failed the request without a retry. Now it retires the session, and the request is retried with another one, up to `max_request_retries` times. A `ThrottlingRequestManager` still defers a 429 from a domain it paces. To fail the request without a retry, as in v1, pass `retry_on_blocked=False`. This option also turns off the check of the response content for blocking. With `proxy_urls`, a session keeps its proxy, so the proxy changes when the session does, not on every request.

Expand Down Expand Up @@ -803,7 +803,7 @@ Session state, including the persisted session pool state, has a new `retired` f

### The session pool creates sessions on demand

`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session_by_id()` no longer creates sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, create the sessions with `get_session()` before you run the crawler.
`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session()` with a session ID doesn't create sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, add the sessions with `add_session()` before you run the crawler.

### Sessions carry their proxy

Expand Down Expand Up @@ -856,6 +856,8 @@ async def main() -> None:

A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. A `context.send_request` call there goes without a proxy.

The crawler fetches robots.txt through the proxy of a session from its session pool, so a proxy from `create_session_settings` or `create_session_function` applies to it too. In v1, the crawler took the proxy from its own `proxy_configuration`. With `respect_robots_txt_file`, enter a passed pool before `add_requests()` too. Otherwise, `add_requests()` raises a `RuntimeError` once it has to fetch a robots.txt file.

### `create_session_function` gets the session options

The `create_session_function` of `SessionPool` now gets a `SessionOptions` dict, the keyword arguments of `Session`, and can be sync or async. The options hold `create_session_settings` and the proxy that the pool's `proxy_configuration` picked, so you can pass `create_session_settings` together with `create_session_function`. The pool also calls the function for every session it restores from the persisted state, with the saved state in the options. Build the session from the options, so that a restored session keeps its state:
Expand Down Expand Up @@ -895,6 +897,93 @@ def create_session(options: SessionOptions) -> Session:
session_pool = SessionPool(create_session_function=create_session)
```

### `get_session()` takes the session ID

`SessionPool.get_session_by_id()` is removed. Pass the ID to `get_session()` instead. With an ID, `get_session()` returns the usable session with this ID or `None`, and doesn't create a session.

### `add_session()` is async and takes session options

`SessionPool.add_session()` is a coroutine and returns the added session. Besides a `Session`, it takes the options of a new session and builds the session from them the same way as the sessions the pool creates: merged over `create_session_settings`, with a proxy from `proxy_configuration`, by `create_session_function`. A passed `Session` is added as it is.

When the pool already holds a usable session with the same ID, `add_session()` raises a `ValueError`. A session with the same ID that's no longer usable is replaced. In v1, `add_session()` logged a warning and kept the old session in both cases.

**Before (v1):**

```python
session_pool.add_session(Session(id='login'))
session = await session_pool.get_session_by_id('login')
```

**Now (v2):**

```python
# highlight-next-line
await session_pool.add_session({'id': 'login'})
# highlight-next-line
session = await session_pool.get_session('login')
```

When `add_session()` has grown the pool beyond `max_pool_size`, `get_session()` creates a new session only if removing the retired sessions leaves room for it. Otherwise, it returns one of the remaining sessions. In v1, it created a new session every time it removed retired sessions.

### A session ID is unique in the pool

The pool holds one usable session per ID. It raises a `ValueError` when:

- `get_session()` gets a session from `create_session_function` with the ID of a usable session already in the pool. Such a function includes one that returns the same `Session` object on every call, so with a `max_pool_size` over 1 the second `get_session()` raises.
- The pool is entered, and the function gives two restored sessions the same ID.
- `create_session_settings` holds an `id`, and `max_pool_size` is over 1.

In v1, a new session silently replaced the session with its ID, so a pool with a fixed session ID and a `max_pool_size` over 1 created new sessions, without the cookies of the old one, on every `get_session()` call. To share one session, pass `max_pool_size=1`. To use several sessions with fixed IDs, add them with `add_session()`.

`get_session()` and `add_session()` also raise a `ValueError` when the session they build is no longer usable, such as a shared session that `create_session_function` returns after it was retired. In v1, the pool returned such a session. When the pool is entered, it drops a restored session that the function recreates unusable.

In a crawler, a `ValueError` from `get_session()` ends the crawl: `run()` raises it after the crawler has tried to get a session three times.

### A crawler takes any session pool

The `session_pool` option of a crawler takes any session pool, not only a `SessionPool`. Such a pool is an async context manager with an `active` property and a `get_session()` method. Without an ID, `get_session()` returns a session. With an ID, it returns the usable session with this ID or `None`. To pass a type checker, declare `get_session()` with these two overloads:

```python
from typing import overload

from crawlee.sessions import Session


class MySessionPool:
@overload
async def get_session(self, session_id: None = None) -> Session: ...

@overload
async def get_session(self, session_id: str) -> Session | None: ...

async def get_session(self, session_id: str | None = None) -> Session | None: ...
```

The sessions need `id`, `cookies`, `proxy_info`, `is_usable`, `mark_good()`, `mark_bad()` and `retire()`. The crawler sends the requests of a session through its `proxy_info`. A crawler with a passed pool doesn't take a `proxy_configuration`, so such a pool picks the proxies of its sessions itself, for example with `ProxyConfiguration.new_proxy_info()`. As with a `SessionPool`, enter the pool before you run the crawler. A request bound by `session_id` to a session that such a pool doesn't return gets a retired session in its failed request handler, even while the pool still holds the session.

`context.session` is typed by these members, so a type checker flags any other `Session` attribute read through it, such as `user_data` or `error_score`. With a `SessionPool`, `context.session` is a `Session`, so cast it:

```python
from typing import cast

from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
from crawlee.sessions import Session

crawler = ParselCrawler()


@crawler.router.default_handler
async def request_handler(context: ParselCrawlingContext) -> None:
session = cast('Session', context.session)
session.user_data['logged_in'] = True
```

### A crawler takes any proxy configuration

The `proxy_configuration` option of a crawler and of a `SessionPool` takes any proxy configuration, not only a `ProxyConfiguration`. Such a configuration has an async `new_proxy_info()` method, which takes the current proxy of the session or `None`, and returns a `ProxyInfo`, or `None` for no proxy. For how it handles the proxy of a restored session, see [Proxy configuration](../concepts/proxy-management#proxy-configuration).

`BasicCrawlerOptions.proxy_configuration` is typed by this method, so a type checker flags any other `ProxyConfiguration` method called through it, such as `new_url()`, and a `new_proxy_info()` call without an argument.

### `max_session_rotations` is removed

Session errors no longer have their own retry budget, the same as in Crawlee JS v4. The `max_session_rotations` crawler option and the `Request.session_rotation_count` property are removed. A `SessionError`, which includes a `ProxyError` and a blocked response, retires the session and counts towards `max_request_retries` like any other error. With the defaults, a request that keeps failing with session errors gets 4 attempts instead of 10. To allow more attempts on blocked requests, raise `max_request_retries`.
Expand Down Expand Up @@ -1606,6 +1695,8 @@ The `ThrottlingRequestManager` warning about capping a delay now calls it a "req

The WARNING `Encountered "<error>", rotating session and retrying...` is removed. Session errors log the same `Retrying request to <url> due to: <error>. <location>` WARNING as other errors. For the other session error changes, see [`max_session_rotations` is removed](#max_session_rotations-is-removed).

`SessionPool.add_session()` no longer logs the `Session with ID ... already exists in the pool.` warning. It raises a `ValueError` for a usable session with the same ID and replaces one that's no longer usable. For details, see [`add_session()` is async and takes session options](#add_session-is-async-and-takes-session-options).

The `Retrying request to ...` WARNING is now logged after the `error_handler` runs, and only when the request is retried. In v1, it was logged before the error handler, so it also appeared when the handler then raised.

The error of an `AdaptivePlaywrightCrawler` sub crawler that timed out now reads `rendering_type=static timed out after 60.0 seconds`, with a space before `seconds`.
Expand Down
5 changes: 3 additions & 2 deletions src/crawlee/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
from crawlee.configuration import Configuration
from crawlee.http_clients import HttpResponse
from crawlee.proxy_configuration import ProxyInfo
from crawlee.sessions import Session, SessionCookies
from crawlee.sessions import SessionCookies
from crawlee.sessions._types import SessionInterface
from crawlee.storage_backends import StorageBackend
from crawlee.storages import KeyValueStore
from crawlee.storages._utils import DatasetItemSnapshots
Expand Down Expand Up @@ -720,7 +721,7 @@ class BasicCrawlingContext:
request: Request
"""Request object for the current page being processed."""

session: Session
session: SessionInterface
"""Session object for the current page being processed."""

proxy_info: ProxyInfo | None
Expand Down
Loading
Loading