### Combine All Features with Batch Solving and Callbacks Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md This example demonstrates combining multiple features, including batch solving, custom callbacks, challenge caching, and browser pooling with proxy configuration. ```python from main import CloudflareSolver, ChallengeType, BrowserPool, ChallengeCache, SolveResult from typing import Optional import asyncio async def main(): cache = ChallengeCache(default_ttl=1800) def on_success(url: str, result: Optional[SolveResult]) -> None: print(f"[OK] {url}") def on_failure(url: str, exc: Optional[Exception]) -> None: print(f"[FAIL] {url} — {exc}") async with BrowserPool(size=3, headless=True, proxy="http://user:pass@host:port") as pool: solver = CloudflareSolver( challenge_type=ChallengeType.CHALLENGE, pool=pool, cache=cache, on_success=on_success, on_failure=on_failure, timeout=60, # seconds per solve call debug=True, retries=30, ) results = await solver.solve_batch(urls, concurrency=pool.size) asyncio.run(main()) ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Installs the required browser binaries for Playwright to function. ```bash playwright install ``` -------------------------------- ### Install Package Dependencies Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Installs the necessary Python package dependencies from the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Browser Pool for Efficient Solving Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Demonstrates using a BrowserPool to keep multiple browsers alive and reuse them across requests, eliminating cold-start overhead. Configure headless, OS, and proxy on the pool. ```python from main import CloudflareSolver, ChallengeType, BrowserPool import asyncio async def main(): async with BrowserPool(size=3, headless=True, os=["windows"]) as pool: solver = CloudflareSolver( challenge_type=ChallengeType.TURNSTILE, pool=pool, ) result = await solver.solve("https://nopecha.com/captcha/turnstile") asyncio.run(main()) ``` -------------------------------- ### Proxy Usage for Cloudflare Solver Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Shows how to configure and use a proxy with the CloudflareSolver for Challenge type challenges. The proxy URL can include authentication credentials. ```python from main import CloudflareSolver, ChallengeType import asyncio async def main(): # "http://user:pass@host:port" || "http://host:port" proxy_url = "http://user:password@123.45.67.89:8080" solver = CloudflareSolver( challenge_type=ChallengeType.CHALLENGE, proxy=proxy_url, headless=True ) result = await solver.solve("https://nopecha.com/demo/cloudflare") if result: print(f"Success! Cookie: {result.value[:20]}...") asyncio.run(main()) ``` -------------------------------- ### Configure Cloudflare Solver with Advanced Options Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md This snippet shows advanced configuration for `CloudflareSolver`, including challenge type, sleep times, headless mode, OS fingerprinting, debugging, retries, proxy, and timeouts. ```python solver = CloudflareSolver( challenge_type=ChallengeType.TURNSTILE, # or ChallengeType.CHALLENGE sleep_time=5, # delay before clicking challenge headless=False, # show browser window os=["macos"], # macOS fingerprint debug=True, # verbose logging + failure screenshots retries=50, # polling attempts for frame / token proxy="http://user:pass@host:port", timeout=90, # abort after 90 s ) ``` -------------------------------- ### Basic Challenge Type Solver Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Demonstrates how to solve a Cloudflare Challenge type using the CloudflareSolver. It initializes the solver for Challenge type and attempts to retrieve a cookie. ```python from main import CloudflareSolver, ChallengeType import asyncio async def main(): solver = CloudflareSolver( challenge_type=ChallengeType.CHALLENGE, headless=True, os=["windows"], ) result = await solver.solve("https://nopecha.com/demo/cloudflare") if result: print(f"Cookie obtained: {result.name}={result.value}") else: print("Failed to solve Cloudflare challenge") asyncio.run(main()) ``` -------------------------------- ### Integrate Callbacks for Success and Failure Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Implement `on_success` and `on_failure` callbacks to hook into the solving pipeline. These can be synchronous or asynchronous functions to handle results or exceptions. ```python from main import CloudflareSolver, ChallengeType, SolveResult from typing import Optional import asyncio # Sync callback def log_success(url: str, result: Optional[SolveResult]) -> None: print(f"[OK] {url}") # Async callback async def alert_failure(url: str, exc: Optional[Exception]) -> None: await some_alerting_service.notify(f"Failed: {url}, reason: {exc}") solver = CloudflareSolver( challenge_type=ChallengeType.TURNSTILE, on_success=log_success, on_failure=alert_failure, ) asyncio.run(solver.solve("https://nopecha.com/captcha/turnstile")) ``` -------------------------------- ### BrowserPool Class Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Manages a pool of pre-warmed Camoufox browsers. Can be used as an async context manager or controlled via start/stop methods. Allows configuration of pool size, headless mode, OS, proxy, and screen size. ```APIDOC ## BrowserPool Class Pool of pre-warmed Camoufox browsers. Use as async context manager or call `start()`/`stop()` manually. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `size` | `int` | `3` | Number of browser instances to keep alive | | `headless` | `bool` | `True` | Headless mode | | `os` | `list[str]` | `["windows"]` | OS fingerprint | | `proxy` | `str | None` | `None` | Proxy URL | | `screen` | `Screen | None` | `None` | Custom screen size (BrowserForge `Screen`) | **Methods:** | Method | Description | |--------|-------------| | `start()` | Launch all browser instances | | `stop()` | Close all browser instances | | `acquire()` | Async context manager that checks out one browser from the pool | ``` -------------------------------- ### Cache Usage for Challenge Solver Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Illustrates how to use ChallengeCache to avoid re-solving the same domain while a result is valid. The TTL is auto-computed from the cookie's expiry for Challenge type. ```python from main import CloudflareSolver, ChallengeType, ChallengeCache import asyncio async def main(): cache = ChallengeCache(default_ttl=1800) # 30 min fallback TTL solver = CloudflareSolver( challenge_type=ChallengeType.CHALLENGE, cache=cache, headless=True, ) # First call: hits the browser result1 = await solver.solve("https://nopecha.com/demo/cloudflare") # Second call: returned from cache instantly result2 = await solver.solve("https://nopecha.com/demo/cloudflare") # Manual invalidation when needed await cache.invalidate("nopecha.com") asyncio.run(main()) ``` -------------------------------- ### Basic Turnstile Type Solver Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Demonstrates how to solve a Cloudflare Turnstile type using the CloudflareSolver. It initializes the solver for Turnstile type and attempts to retrieve a token. ```python from main import CloudflareSolver, ChallengeType import asyncio async def main(): solver = CloudflareSolver( challenge_type=ChallengeType.TURNSTILE, headless=True, os=["windows"], ) result = await solver.solve("https://nopecha.com/captcha/turnstile") if result: print(f"Token obtained: {result.token}") else: print("Failed to solve Turnstile challenge") asyncio.run(main()) ``` -------------------------------- ### Solve Multiple URLs Concurrently Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Use `solve_batch` to process a list of URLs concurrently. Results are returned in the same order as the input URLs. Ensure a `BrowserPool` is set up for managing browser instances. ```python from main import CloudflareSolver, ChallengeType, BrowserPool import asyncio async def main(): urls = [ "https://site-a.com/page", "https://site-b.com/page", "https://site-c.com/page", ] async with BrowserPool(size=3, headless=True) as pool: solver = CloudflareSolver( challenge_type=ChallengeType.CHALLENGE, pool=pool, ) # concurrency=pool.size prevents over-saturating the pool results = await solver.solve_batch(urls, concurrency=pool.size) for url, result in zip(urls, results): if result: print(f"{url} -> {result.value[:20]}...") asyncio.run(main()) ``` -------------------------------- ### ChallengeCache Class Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md A TTL-aware in-memory cache for challenge results. Cache hits can bypass the browser entirely. It supports setting default TTL, storing results with optional TTL, and invalidating or clearing entries. ```APIDOC ## ChallengeCache Class TTL-aware in-memory result cache. Cache hits skip the browser entirely. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `default_ttl` | `float` | `1800.0` | Fallback TTL in seconds when expiry cannot be derived from the result | **Methods:** | Method | Description | |--------|-------------| | `get(domain, challenge_type)` | Return cached result or `None` if missing / expired | | `set(domain, challenge_type, result, ttl=None)` | Store result; `ttl` auto-computed from cookie expiry when `None` | | `invalidate(domain, challenge_type=None)` | Evict one or all challenge types for a domain | | `clear()` | Clear all entries | ``` -------------------------------- ### CloudflareSolver Class Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md The main class for solving Cloudflare challenges. It can be configured with various parameters including challenge type, headless mode, proxy, and browser pool. It supports solving single URLs or batches of URLs. ```APIDOC ## CloudflareSolver Class #### Parameters: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `challenge_type` | `ChallengeType` | `CHALLENGE` | `CHALLENGE` (cookie) or `TURNSTILE` (token) | | `sleep_time` | `int` | `5` | Seconds to wait before clicking checkbox | | `headless` | `bool` | `True` | Headless mode (ignored when `pool` is set) | | `os` | `list[str]` | `["windows"]` | OS fingerprint (ignored when `pool` is set) | | `debug` | `bool` | `False` | Verbose logging + failure screenshots | | `retries` | `int` | `30` | Polling attempts for frame/token detection | | `proxy` | `str | None` | `None` | Proxy URL (ignored when `pool` is set) | | `pool` | `BrowserPool | None` | `None` | Pre-warmed browser pool | | `cache` | `ChallengeCache | None` | `None` | Result cache | | `on_success` | `Callback | None` | `None` | Called with `(url, result)` on success (sync or async) | | `on_failure` | `Callback | None` | `None` | Called with `(url, exc_or_none)` on failure (sync or async) | | `timeout` | `float | None` | `None` | Per-call timeout in seconds | #### Methods: | Method | Description | |--------|-------------| | `solve(link)` | Solve challenge for one URL. Returns `CloudflareCookie`, `TurnstileToken`, or `None` | | `solve_batch(links, concurrency=None)` | Solve multiple URLs in parallel. Returns list in input order. `concurrency` caps simultaneous solves | ``` -------------------------------- ### ChallengeType Enum Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Defines the type of Cloudflare challenge to solve. Use CHALLENGE for traditional challenges returning a cf_clearance cookie, or TURNSTILE for Turnstile challenges returning a token. ```APIDOC ## ChallengeType Enum Defines the type of Cloudflare challenge to solve: - `CHALLENGE` - Traditional challenge that returns `cf_clearance` cookie - `TURNSTILE` - Turnstile challenge that returns a token from hidden input field ``` -------------------------------- ### CloudflareCookie Dataclass Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Represents the Cloudflare clearance cookie, containing details like name, value, domain, path, expiration, and security flags. ```APIDOC ## CloudflareCookie Dataclass Represents the Cloudflare clearance cookie (for Challenge type): - `name`: Cookie name (typically "cf_clearance") - `value`: Cookie value - `domain`: Cookie domain - `path`: Cookie path - `expires`: Expiration timestamp - `http_only`: HTTP Only flag - `secure`: Secure flag - `same_site`: SameSite policy ``` -------------------------------- ### TurnstileToken Dataclass Source: https://github.com/art3m4ik3/cloudflare-solver/blob/main/README.md Represents the Turnstile token, which is the token value extracted from the cf-turnstile-response input field. ```APIDOC ## TurnstileToken Dataclass Represents the Turnstile token (for Turnstile type): - `token`: Token value extracted from `cf-turnstile-response` input field ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.