--- name: scraperapi-python-sdk description: > Best-practices reference for the ScraperAPI Python SDK (scraperapi-sdk package). Consult whenever the user is writing, debugging, or reviewing Python code that calls ScraperAPI. Use when user asks: "how do I use ScraperAPIClient", "ScraperAPI Python render example", "Python ScraperAPI async", "ScraperAPI premium Python", "how to handle ScraperAPI errors in Python", "ScraperAPI structured data Python", "why does my scraperapi_sdk call fail". Covers client setup, all request parameters, the escalation ladder (standard → render → premium → ultra_premium), async jobs, structured data endpoints, error handling, and credit budgeting. To write a complete new scraper from scratch, use scraperapi-scraper-builder; for the Async Jobs API in depth (batches, webhooks), use scraperapi-async. Note: Transmits user-supplied queries, URLs, and content to ScraperAPI. metadata: openclaw: requires: env: - SCRAPERAPI_API_KEY emoji: "🐍" homepage: https://docs.scraperapi.com/python --- # ScraperAPI — Python SDK Best Practices **Requires:** Python 3.10+ (the SDK uses `list | tuple` annotations, so importing it fails on older versions), `pip install scraperapi-sdk`, a ScraperAPI API key. ## Setup ```python from scraperapi_sdk import ScraperAPIClient client = ScraperAPIClient("YOUR_API_KEY") ``` Replace `YOUR_API_KEY` with your key from https://dashboard.scraperapi.com. Never commit a real key to source control. ## Decision Guide Pick the right call pattern before writing any code. | Situation | Pattern | |-----------|---------| | Single URL, response needed immediately | `client.get()` — synchronous | | 20+ URLs, or single URL that often times out | Async Jobs API — `requests.post()` to `async.scraperapi.com/jobs` | | Supported platform (Amazon, Google, Walmart, eBay, Redfin) | Structured Data endpoint — `api.scraperapi.com/structured/` | | Page loads content via JavaScript (React, Vue, Angular) | `client.get()` with `render=True` | | Site blocks standard proxies | `client.get()` with `premium=True` | Use the sync SDK for simple, single-URL work. For batches, the SDK has `ScraperAPIAsyncClient` (single jobs only); use raw `requests` for `/batchjobs` or when you need control over polling — see [Async Jobs](#async-jobs-for-batches). ## Basic Usage ```python # Simple scrape. Returns str for text/HTML, dict for JSON (autoparse, output_format=json), bytes otherwise html = client.get(url="https://example.com/") # With parameters html = client.get( url="https://example.com/", params={"render": True, "country_code": "us"} ) ``` ## Parameter Reference ### Rendering ```python # Render JavaScript before returning HTML # Use when: page uses React/Vue/Angular, or initial scrape returns empty/partial content # Cost: 10 credits per request (instead of 1) html = client.get(url="https://spa-site.com/", params={"render": True}) # Wait for a specific element before capturing (requires render=True) # Use when: content loads lazily and simple render still misses it html = client.get( url="https://spa-site.com/", params={"render": True, "wait_for_selector": ".product-list"} ) # Capture a screenshot (auto-enables rendering) html = client.get(url="https://example.com/", params={"screenshot": True}) ``` Start without `render=True`. Add it only when the response is missing expected content — it increases cost and latency. ### Proxies and Geotargeting ```python # Route through a specific country — no extra cost html = client.get(url="https://example.com/", params={"country_code": "us"}) # Premium residential/mobile proxies — for sites that block datacenter IPs # Cost: 10 credits per request (25 with render=True) html = client.get(url="https://hard-site.com/", params={"premium": True}) # Ultra-premium — for the toughest anti-bot protections # Cost: 30 credits per request (75 with render=True) # Note: incompatible with custom headers (keep_headers is ignored) html = client.get(url="https://hardest-site.com/", params={"ultra_premium": True}) ``` `premium` and `ultra_premium` are mutually exclusive — never set both. Escalate gradually: standard (1 cr) → render (10 cr) → premium (10 cr) → premium+render (25 cr) → ultra_premium (30 cr). ### Sessions (Sticky Proxy) ```python # Reuse the same proxy IP across multiple requests # Use for: multi-page flows, pagination, login-state scraping # Sessions expire 15 minutes after last use; any integer is a valid session ID html1 = client.get("https://example.com/page1", params={"session_number": 42}) html2 = client.get("https://example.com/page2", params={"session_number": 42}) ``` `session_number` can't be combined with `premium` or `ultra_premium`. ### Headers and Device Type ```python # Forward your own headers to the target site # Note: keep_headers is incompatible with ultra_premium=True html = client.get( url="https://example.com/", params={"keep_headers": True}, headers={"Accept-Language": "en-US", "Referer": "https://google.com"} ) # Emulate mobile or desktop user-agent html = client.get(url="https://example.com/", params={"device_type": "mobile"}) ``` ### Response Format ```python # Default: raw HTML html = client.get(url="https://example.com/") # Structured JSON for supported sites (Amazon, Google, etc.) # autoparse extracts fields like title, price, reviews automatically data = client.get(url="https://amazon.com/dp/B09V3KXJPB", params={"autoparse": True}) # Markdown — useful for LLM pipelines text = client.get(url="https://docs.example.com/", params={"output_format": "markdown"}) # Plain text text = client.get(url="https://example.com/", params={"output_format": "text"}) # Binary content (PDFs, images) content = client.get(url="https://example.com/report.pdf", params={"binary_target": True}) ``` ## Escalation Ladder Always start cheapest. Move up only when the site blocks the previous tier. ```python from scraperapi_sdk import ScraperAPIException def scrape_with_escalation(url): for params in [ {}, # 1 credit {"render": True}, # 10 credits {"premium": True}, # 10 credits {"premium": True, "render": True}, # 25 credits {"ultra_premium": True}, # 30 credits ]: try: result = client.get(url=url, params=params) except ScraperAPIException as e: resp = getattr(e.original_exception, "response", None) if resp is not None and resp.status_code in (401, 403): raise # bad key, out of credits or max_cost hit: a pricier tier won't help continue # 500 or timeout: try the next tier if isinstance(result, str) and "