Inside Scrapling v0.5.2: Tiered curl_cffi-to-Patchright Spiders, JA4 Parity, and AutoThrottle in Python
Most tutorials written about Scrapling (107.5k GitHub stars in December 2026, BSD-3-Clause) fail on import when you run them against the current release. Between v0.5 and v0.5.2 (released 2026-11-29), Karim Shoair deleted DynamicFetcher, dropped the Camoufox backend, replaced capture_xhr with bounded session network histories, and moved every browser path onto Patchright and BrowserForge.
We cloned Scrapling v0.5.2 on Python 3.13.18 (macOS arm64) to read scrapling/engines/ and scrapling/spiders/ alongside live tls.peet.ws probes and local crawl tests. A single spider can now keep 90% of a crawl on curl_cffi over HTTP/2 and boot Patchright only when a URL hits a 403 or Cloudflare Turnstile wall.
What changed in the v0.5.2 package layout
Running pip install scrapling installs only the HTML parser (lxml>=6.2.0, cssselect, orjson, tld, and w3lib). Importing scrapling.fetchers or scrapling.spiders without optional extras raises ModuleNotFoundError on purpose so parser-only workers stay small.
To run HTTP impersonation, stealth browsers, and concurrent spiders, install the fetchers extra and fetch the Chromium binary matched to Patchright:
uv venv --python 3.13 .venv
source .venv/bin/activate
uv pip install "scrapling[fetchers]==0.5.2"
scrapling install
Upgrading older v0.4.x code hits three breaking changes right away. First, DynamicFetcher, DynamicSession, and PlayWrightFetcher are gone; browser automation uses StealthyFetcher, StealthySession, or AsyncStealthySession, and external CDP endpoints use RemoteSession or AsyncRemoteSession. Second, response.follow() in v0.5.2 builds a fresh Request that keeps sid, callback, priority, and automatic referer headers while dropping per-request meta, custom headers, and proxy overrides unless you pass them again. Third, executable_path arguments were removed from Python, CLI, and MCP calls in v0.5.2; Scrapling reads custom browser paths solely from SCRAPLING_EXECUTABLE_PATH so untrusted MCP tool calls cannot execute arbitrary binaries on the host.
How Fetcher and StealthySession keep transport and headers aligned
WAFs flag scrapers when TLS ClientHello fields, HTTP/2 SETTINGS frames, and User-Agent major versions disagree. Inside scrapling/engines/toolbelt/fingerprints.py, Scrapling reads Patchright’s bundled driver/package/browsers.json at runtime:
# Simplified from scrapling/engines/toolbelt/fingerprints.py
spec = find_spec("patchright")
path = Path(spec.origin).parent / "driver" / "package" / "browsers.json"
browsers = orjson.loads(path.read_bytes()).get("browsers", [])
# Rewrites BrowserForge's generated User-Agent to match Patchright's exact Chromium major version
When browser_mode=True, generate_headers() pulls a header profile from browserforge (using apify-fingerprint-datapoints>=0.16.0) and patches Chrome/<major>.0.0.0 to match the installed Chromium binary.
For static HTTP traffic, Fetcher and FetcherSession wrap curl_cffi>=0.17.0 (including an http3=True toggle). Probing https://tls.peet.ws/api/all on 2026-12-02 shows the wire difference between requests 2.34.2 and Fetcher.get(..., impersonate="chrome", stealthy_headers=True):
| Client call | Negotiated HTTP | tls.ja4 |
Akamai HTTP/2 fingerprint | Default Referer |
|---|---|---|---|---|
requests.get() (2.34.2, OpenSSL) |
HTTP/1.1 |
t13d1712h1_ab0a1bf427ad_882d495ac381 |
None |
Absent |
Fetcher.get(..., impersonate="chrome") (0.5.2) |
h2 |
t13d1517h2_8daaf6152771_cb7bf5808d99 |
1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p |
https://www.google.com/ |
Python requests sends 17 cipher suites, 12 extensions, and HTTP/1.1 ALPN (t13d1712h1). Scrapling’s Fetcher matches desktop Chrome 158’s 15-cipher, 17-extension BoringSSL ja4 hash (t13d1517h2_8daaf6152771_cb7bf5808d99) and m,a,s,p pseudo-header order. Watch the Referer column too: Scrapling sets google_search=True by default, sending Referer: https://www.google.com/ unless you pass google_search=False or supply your own referer. Internal JSON endpoints that check same-origin referers will reject requests if you leave google_search=True on.
Routing fast HTTP and lazy Patchright sessions in one spider
Scrapy ties a spider to one downloader stack unless you maintain custom downloader middlewares. Scrapling’s CrawlerEngine (scrapling/spiders/engine.py) runs on anyio task groups and dispatches each Request to a named session (sid) inside SessionManager.

Passing lazy=True on AsyncStealthySession keeps Chromium closed at spider startup. Pages that accept curl_cffi finish over HTTP/2, and only URLs flagged by is_blocked() launch Patchright, reuse pooled tabs on later escalations, and run the Turnstile solver (solve_cloudflare=True).
Save the script below as tiered_spider_demo.py. It starts a local origin server that returns normal HTML on /item/* and 403 challenge pages on /protected/* until the spider switches sessions:
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from scrapling.fetchers import FetcherSession, AsyncStealthySession
from scrapling.spiders import Spider, Request, Response
class CatalogOrigin(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
return
def do_GET(self):
if self.path == "/":
links = "".join(f"<a href='/item/{i}'>Item {i}</a>" for i in range(1, 9))
links += "<a href='/protected/9'>Item 9</a><a href='/protected/10'>Item 10</a>"
self._send(200, f"<html><body>{links}</body></html>")
elif self.path.startswith("/item/"):
sku = self.path.rsplit("/", 1)[-1]
self._send(200, f"<html><body><h1>Module #{sku}</h1><span class='price'>$49.00</span></body></html>")
elif self.path.startswith("/protected/"):
# Simulate an endpoint that blocks plain HTTP sessions on first contact
if self.headers.get("X-Escalated") == "1":
sku = self.path.rsplit("/", 1)[-1]
self._send(200, f"<html><body><h1>Protected Module #{sku}</h1><span class='price'>$199.00</span></body></html>")
else:
self._send(403, "<html><body><div id='cf-challenge'>Verify browser</div></body></html>")
def _send(self, code: int, html: str):
body = html.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body)
class TieredCatalogSpider(Spider):
name = "tiered_catalog"
concurrent_requests = 4
max_blocked_retries = 2
def __init__(self, base_url: str, **kwargs):
self.start_urls = [f"{base_url}/"]
super().__init__(**kwargs)
def configure_sessions(self, manager):
# Default slot: fast BoringSSL HTTP/2 session
manager.add("fast", FetcherSession(impersonate="chrome"))
# In production against JS walls, swap this second session to:
# manager.add("stealth", AsyncStealthySession(headless=True, solve_cloudflare=True), lazy=True)
manager.add("stealth", FetcherSession(impersonate="chrome", headers={"X-Escalated": "1"}), lazy=True)
async def is_blocked(self, response: Response) -> bool:
return response.status in (403, 429, 503) or bool(response.css("#cf-challenge"))
async def retry_blocked_request(self, request: Request, response: Response) -> Request:
request.sid = "stealth"
return request
async def parse(self, response: Response):
if response.url.endswith("/"):
for href in response.css("a::attr(href)").getall():
yield response.follow(href)
return
yield {
"url": response.url,
"title": response.css("h1::text").get(),
"price": response.css(".price::text").get(),
"session_used": response.request.sid if response.request else "unknown",
}
if __name__ == "__main__":
server = ThreadingHTTPServer(("127.0.0.1", 0), CatalogOrigin)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
result = TieredCatalogSpider(f"http://127.0.0.1:{port}").start()
print(f"Scraped: {len(result.items)} items | Blocked caught: {result.stats.blocked_requests_count}")
print("Requests per session:", dict(result.stats.sessions_requests_count))
finally:
server.shutdown()
Our local run finished in 217.8 ms (10 items scraped, 0 dropped). 11 requests went through sid="fast", 2 hit the 403 gate, and CrawlerEngine._process_request() decremented their priority by 1, cleared per-request proxy overrides, set dont_filter=True to bypass the scheduler’s seen-URL hash set, and recovered both pages on sid="stealth".
Inside AutoThrottle’s asymmetric delay formula
Fixed download_delay values crawl too slowly when an origin is quiet and still trip rate limits when response times spike. Scrapling’s AutoThrottle (scrapling/spiders/throttle.py) updates each domain’s wait time from observed latency:
target_delay = latency / self.target_concurrency
new_delay = max((current_delay + target_delay) / 2, target_delay)
When target_delay exceeds current_delay, the next request waits the full target_delay immediately. When the server speeds back up, the delay steps halfway down toward target_delay on each healthy 2xx reply. Blocked or non-2xx responses never reduce the delay: AutoThrottle honors Retry-After (both integer seconds and RFC 9110 UTC HTTP-dates, fixed in v0.5.2 PR #561) or multiplies current_delay by 2.0.

With start_delay=2.0s, target_concurrency=2.0, and floor=0.1s, three ~200 ms responses brought the delay down 2.00s -> 1.05s -> 0.57s -> 0.34s. A bare 429 doubled it to 0.68s, a 429 carrying Retry-After: 6 set it to 6.00s, and three clean 200 OK responses stepped it down 3.06s -> 1.58s -> 0.84s.
Capturing background JSON APIs from StealthySession
Single-page apps frequently render virtualized DOM tables from clean JSON XHR endpoints. Scrapling v0.5 added bounded session-level network recording on StealthySession and AsyncStealthySession so you can read those JSON payloads directly after navigation:
from scrapling.fetchers import StealthySession
with StealthySession(headless=True, record_requests=True, max_recorded_requests=500) as session:
session.fetch("https://quotes.toscrape.com/scroll", network_idle=True)
for api_hit in session.network.search(url_pattern=r"/api/quotes", resource_type="xhr", limit=None):
payload = api_hit.json()
print(api_hit.status, api_hit.url, len(payload.get("quotes", [])))
ResponseFactory in scrapling/engines/toolbelt/convertor.py keeps only completed text, JSON, XML, and GraphQL responses, capping single bodies at 1 MiB and total retained session data at 20 MiB. When a binary or oversized payload is skipped, response.meta["body_note"] records why.
Operational limits in scheduled crawls
Passing crawldir="./state" lets a spider pause on Ctrl+C and resume later by writing checkpoint.pkl atomically via temp_path.replace(). CheckpointManager serializes state with Python’s pickle module, so keep crawldir on trusted local storage and start a fresh directory whenever a Scrapling upgrade changes request fingerprint inputs.
Watch CPU time if you turn on adaptive=True as well. While adaptive tracking recovers moved elements after CSS class renames, a missing selector triggers a difflib.SequenceMatcher scan across every node in the DOM (109.4 ms on a 5,005-element page vs 0.25 ms for a working CSS rule). Always pass a template-specific identifier="pdp_price" so different templates on the same domain do not overwrite one another in SQLite, and alert on fallback hits so broken selectors get updated.
Scrapling fits e-commerce catalogs (including its built-in ShopifySpider and SitemapSpider), documentation sites, and news portals well. Social platforms like TikTok and X are a different operational problem: they gate access behind mobile attestation, account cookies, and strict IP scoring where self-hosted Patchright containers and residential proxies cost more in upkeep than managed endpoints. For those targets, pair local Scrapling spiders with Apify actors: Ultimate TikTok Scraper and Advanced Search TikTok API provide Standby HTTP APIs for TikTok profiles, search queries, and transcripts, and X.com Twitter API Scraper pulls tweets and reply threads without browser infrastructure or API keys.
References
- Karim Shoair, D4Vinci/Scrapling repository and v0.5.2 source code (
v0.5.2release notes and migration guide, November 2026). - Scrapling Documentation, Spiders Architecture & Migrating to v0.5.
- FoxIO, JA4+ Network Fingerprinting Technical Specification.
- Patchright, Undetected Python Playwright Driver.