Docs/API reference

Session · Python

Own shared request defaults, connection pools, per-host pacing and retry settings.

Download .md
Developers10 min read39 sections
Source reference · Match your SDK version. Availability and known issues
In this guide

Purpose and lifecycle

Create one session per site or authentication identity and pass it to related operations. Configuration setters return the same session. Settings are held in the Rust engine.

Set authentication and response-cache middleware before the first fetch. A clone copies request configuration but starts independent pools, metrics and middleware. It does not inherit installed auth/cache layers.

Cookies are explicitly configured request defaults, not a browser cookie jar. They have no domain, path or expiry attributes and Set-Cookie responses are not automatically persisted.

Python retry and cookie-management methods are in development source and are not included in the existing alpha.2 package; they require a later release or a matching source build.

Definition and availability

Source snapshot: 1.0.0-alpha.3. Package export. Declared in source; this is not a runtime test result.

Signatures and source locations are generated from the SDK wrappers. Clean snapshots link to the recorded commit. Modified snapshots link to main, which may differ; file hashes identify the local inputs.

class Session
python1 lines · copy-ready

Usage example

Use a matching source build. Where a snippet uses page, obtain it with the Page example first. Example URLs illustrate API shape; they are not promised datasets.

from crawlingo import Session, Dataset

# These retry and cookie methods require the development source.
session = Session().rate_limit(2).timeout(30)
session.retries(3).retry_delay(1).retry_backoff(2)
session.cookies({"locale": "en"})
print(session.get_cookies())
session.delete_cookie("locale").clear_cookies()
session.headers({"User-Agent": "ResearchDataset/1.0"})
result = Dataset("https://example.com/", session=session).field("title", "h1").build()
print(result.to_dict())
python11 lines · copy-ready

Members

MemberKindReturn / value typeSource status
__init__methodNot annotated; see behavior notesPresent in source
headersmethod'Session'Present in source
cookiesmethod'Session'Present in source
get_cookiesmethoddictPresent in source
delete_cookiemethod'Session'Present in source
clear_cookiesmethod'Session'Present in source
retriesmethod'Session'Present in source
retry_backoffmethod'Session'Present in source
retry_delaymethod'Session'Present in source
proxymethod'Session'Present in source
rate_limitmethod'Session'Present in source
auto_matchmethod'Session'Present in source
timeoutmethod'Session'Present in source
fingerprint_pathmethod'Session'Present in source
fetcher_tiermethod'Session'Present in source
browser_profilemethod'Session'Present in source
auto_match_weightsmethod'Session'Present in source
proxy_poolmethod'Session'Present in source
proxy_providermethod'Session'Present in source
enable_response_cachemethod'Session'Present in source
basic_authmethod'Session'Present in source
bearer_authmethod'Session'Present in source
header_authmethod'Session'Present in source
api_key_authmethod'Session'Present in source
from_configstatic method'Session'Present in source
metricsmethoddictPresent in source
pagemethod'Page'Present in source
datasetmethod'Dataset'Present in source
watchmethod'Watch'Present in source
crawlmethod'Crawl'Present in source
clonemethod'Session'Present in source
destroymethodNonePresent in source
__enter__method'Session'Present in source
__exit__methodNot annotated; see behavior notesPresent in source

__init__()

Create an empty session with a 30-second request timeout, standard HTTP transport and no pacing limit. No request is sent by construction.

Returns / value: Not annotated; see behavior notes.

def __init__(self)
python1 lines · copy-ready

headers()

Replace the entire default header map. Node Page.create merges its request headers over this map. Authentication headers apply to every request using this session.

Returns / value: 'Session'.

def headers(self, headers: dict) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
headersdictRequiredHeader names and values; avoid sharing credentials across unrelated sites.

cookies()

Replace the entire explicit cookie map. Use a different session for another authentication identity.

Returns / value: 'Session'.

def cookies(self, cookies: dict) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
cookiesdictRequiredExplicit cookie-name/value defaults.

get_cookies()

Return a snapshot of configured cookies. Mutating the returned object does not mutate the session.

Returns / value: dict.

def get_cookies(self) -> dict
python1 lines · copy-ready

clear_cookies()

Remove all explicit cookie defaults. This does not clear an independently supplied Cookie header.

Returns / value: 'Session'.

def clear_cookies(self) -> 'Session'
python1 lines · copy-ready

retries()

Set additional attempts after the initial request. 0 means one attempt. Integers 0–4294967295 are accepted. Default Page/Dataset/Crawl/Job retry count is 3; downloader/sitemap defaults can differ until explicitly set.

Returns / value: 'Session'.

def retries(self, count: int) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
countintRequiredCount of additional retries after the initial attempt.

retry_backoff()

Set a finite exponential multiplier >= 1. Delay for retry n starts at base × factor^n, capped by policy. Default factor is 2. In development source, Retry-After in seconds or HTTP-date form takes precedence when enabled; older releases support seconds only. Changes affect subsequent dispatches without rebuilding pools.

Returns / value: 'Session'.

def retry_backoff(self, factor: float) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
factorfloatRequiredFinite multiplier, at least 1.

retry_delay()

Set initial backoff in whole seconds, from 0 to 86400. The default policy uses 500 ms; use shared configuration for fractional-second timing. Computed delay is capped at max(configured maximum, initial delay).

Returns / value: 'Session'.

def retry_delay(self, seconds: int) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
secondsintRequiredTime in seconds; see the method-specific range and timing semantics.

proxy()

Set a static proxy URL. A static proxy takes priority over the rotation pool. HTTP(S) and supported SOCKS proxy behavior depends on the compiled HTTP client.

Returns / value: 'Session'.

def proxy(self, proxy_url: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
proxy_urlstrRequiredProxy endpoint URL accepted by the compiled HTTP transport.

rate_limit()

Set the shared per-host request rate in requests per second. 0 disables configured pacing. This is not a global limit across separate sessions or machines.

Returns / value: 'Session'.

def rate_limit(self, requests_per_second: float) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
requests_per_secondfloatRequiredPer-host rate for the shared session.

auto_match()

Enable heuristic CSS fingerprint recovery for the Dataset builder. It does not enable selector recovery in DatasetJob or execute JavaScript.

Returns / value: 'Session'.

def auto_match(self, enabled: bool) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
enabledboolRequiredEnable or disable this behavior.

timeout()

Set the per-attempt timeout in seconds. Total time can exceed it because of retries, backoff and rate-limit waits.

Returns / value: 'Session'.

def timeout(self, seconds: int) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
secondsintRequiredTime in seconds; see the method-specific range and timing semantics.

fingerprint_path()

Select the local directory used for lazily opened fingerprint storage. Keep one coherent identity/history for a selector; a new path has no recovery history.

Returns / value: 'Session'.

def fingerprint_path(self, path: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
pathstrRequiredFilesystem path relative to the process working directory unless absolute.

fetcher_tier()

Node exposes standard and stealthy HTTP tiers. Python can request browser only when its native build includes the browser feature and local Chromium is available. Stealth emulation does not guarantee access.

Returns / value: 'Session'.

def fetcher_tier(self, tier: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
tierstrRequiredTransport mode supported by this binding and native build.

browser_profile()

Choose a supported HTTP impersonation profile: chrome, firefox or safari. A profile changes transport emulation; it does not launch a browser.

Returns / value: 'Session'.

def browser_profile(self, profile: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
profilestrRequiredHTTP impersonation profile; this does not launch a browser.

auto_match_weights()

Set scoring weights used by the heuristic matcher. Similarity scores are not calibrated probabilities; validate recovered field values.

Returns / value: 'Session'.

def auto_match_weights(self, weights: dict) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
weightsdictRequiredNamed heuristic matching weights. Review extracted values after changing scores.

proxy_pool()

Replace the pool of proxy URLs used in round-robin order when no static proxy is set. This is configuration, not a proxy health-check service.

Returns / value: 'Session'.

def proxy_pool(self, proxies: list) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
proxieslistRequiredProxy URL list used when no static proxy is configured.

proxy_provider()

Fetch proxy entries from the configured provider endpoint. The Node binding currently discards a provider-fetch error; do not treat this setter returning as proof that proxies were loaded.

Returns / value: 'Session'.

def proxy_provider(self, url: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
urlstrRequiredHTTP(S) source URL; verify the target is appropriate for your application.

enable_response_cache()

Install in-memory response caching before first fetch. max_entries bounds entry count; default_ttl_seconds is the fallback freshness lifetime. Cache headers and validators still apply.

Returns / value: 'Session'.

def enable_response_cache(self, max_entries: int=1024, default_ttl_seconds: int=300) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
max_entriesintDefault: 1024Maximum number of cached responses, not a total byte limit.
default_ttl_secondsintDefault: 300Fallback cache lifetime in seconds.

basic_auth()

Install HTTP Basic Authorization middleware before the first request. Pass credentials through application configuration; do not embed them in example source.

Returns / value: 'Session'.

def basic_auth(self, username: str, password: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
usernamestrRequiredHTTP Basic username from application configuration.
passwordstrRequiredHTTP Basic password; obtain it from protected application configuration.

bearer_auth()

Install a fixed Bearer token header before first fetch. Refresh or rotation is owned by your application.

Returns / value: 'Session'.

def bearer_auth(self, token: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
tokenstrRequiredBearer credential managed by the application.

header_auth()

Install a named authentication header before the first fetch.

Returns / value: 'Session'.

def header_auth(self, name: str, value: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
namestrRequiredField, header or attribute name for this operation.
valuestrRequiredHeader or query value for the configured authentication method.

api_key_auth()

Append an API-key query parameter to outgoing request URLs. Query values may appear in access logs; use a header where the upstream supports it.

Returns / value: 'Session'.

def api_key_auth(self, name: str, value: str) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
namestrRequiredField, header or attribute name for this operation.
valuestrRequiredHeader or query value for the configured authentication method.

from_config()

Load TOML or JSON, apply CRAWLINGO_* environment overrides and validate configuration. Omit the path to load defaults plus environment only. Explicit setters applied afterward override loaded settings.

Returns / value: 'Session'.

def from_config(cls, path: Optional[str]=None) -> 'Session'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
pathOptional[str]Default: NoneFilesystem path relative to the process working directory unless absolute.

metrics()

Return a snapshot of fetch counts, statuses, per-host activity and latency. These are session metrics, not the DatasetJob record-quality report.

Returns / value: dict.

def metrics(self) -> dict
python1 lines · copy-ready

page()

Create a lazy Python Page attached to the session. Python Page currently supplies its own default timeout=30 and retries=3; pass explicit Page options when those values matter.

Returns / value: 'Page'.

def page(self, url: str) -> 'Page'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
urlstrRequiredHTTP(S) source URL; verify the target is appropriate for your application.

dataset()

Create a Dataset builder attached to this session. Add fields and call build to fetch.

Returns / value: 'Dataset'.

def dataset(self, url: str) -> 'Dataset'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
urlstrRequiredHTTP(S) source URL; verify the target is appropriate for your application.

watch()

Create a field-monitoring Watch handle. Register fields and callbacks before starting it.

Returns / value: 'Watch'.

def watch(self, url: str) -> 'Watch'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
urlstrRequiredHTTP(S) source URL; verify the target is appropriate for your application.

crawl()

Create a Python Crawl wrapper. Review its documented native-binding gaps before use.

Returns / value: 'Crawl'.

def crawl(self, url: str) -> 'Crawl'
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
urlstrRequiredHTTP(S) source URL; verify the target is appropriate for your application.

clone()

Return an independent session with copied defaults and retry settings. Cookie changes on the clone do not affect the original. Middleware is not cloned.

Returns / value: 'Session'.

def clone(self) -> 'Session'
python1 lines · copy-ready

destroy()

Clear selected native state and drop cached managers when no operation retains them. This is cleanup, not cancellation of running jobs. Await owned work before cleanup.

Returns / value: None.

def destroy(self) -> None
python1 lines · copy-ready

__enter__()

Return the same Python session for a with block.

Returns / value: 'Session'.

def __enter__(self) -> 'Session'
python1 lines · copy-ready

__exit__()

The current Python context-manager exit is a no-op. It does not call destroy; manage cleanup explicitly.

Returns / value: Not annotated; see behavior notes.

def __exit__(self, exc_type, exc_val, exc_tb)
python1 lines · copy-ready
ParameterTypeRequired / defaultMeaning
exc_typeNot annotatedRequiredException class supplied by the Python with statement, or None.
exc_valNot annotatedRequiredException instance supplied by the Python with statement, or None.
exc_tbNot annotatedRequiredTraceback supplied by the Python with statement, or None.

Errors and operational limits

Node retry setters reject invalid numbers with RangeError. Native configuration failures use CrawlingoError; Python session methods can propagate native RuntimeError or ValueError directly. Do not assume identical exception translation across bindings.

Source availability, package publication and runtime validation are separate facts. These pages describe the source snapshot, not a claim that all platforms or every API path have passed production acceptance.