ScraperFlyAI-ready Web Data API

developer api

Python Web Scraping API example for public page capture

Use ScraperFly as the capture layer for Python scraping workflows: test a public URL, choose HTML, text, Markdown, JSON metadata, screenshot, or PDF output, add rendering or routing only when the target needs it, then pass the response into scripts, notebooks, queues, or data pipelines.

Python workflow

Use Python for the data work and ScraperFly for page capture

Python is a strong place to parse, validate, store, analyze, and move web data through jobs, notebooks, queues, and AI pipelines. It is a poor use of time to make every Python project maintain browser workers, proxy routing, screenshot capture, PDF generation, retry logic, and output converters before the page response is even proven.

ScraperFly gives Python teams one hosted capture layer for public pages. Start with a real URL, choose the response shape your code can use, inspect the evidence, and add rendering, sessions, headers, country targeting, waits, or stronger routing only when the target shows they improve the result.

requests or httpxnotebooksdata pipelines
Developer using Python with a web scraping API response workflow

How do you use a web scraping API from Python?

Use Python to send a public target URL and request options to a hosted web scraping API, then process the returned response in your own code. The API handles page capture, rendering when needed, routing controls, sessions, headers, and output formats. Python handles parsing, validation, storage, scheduling, data quality checks, alerts, and downstream business logic.

This split keeps the workflow practical. A small script can call ScraperFly with a target URL, request HTML, text, Markdown, JSON metadata, a screenshot, or a PDF, and then pass that response to BeautifulSoup, lxml, pandas, a database loader, a queue worker, or an AI ingestion step. The request profile stays explicit instead of being buried across browser code, proxy glue, custom retries, and converters.

Practical takeaway: let ScraperFly capture the public page reliably, then let Python do the data work your product actually owns.

What should the first Python scraping script prove?

The first script should prove the target, not the whole production system. Send one representative URL, request the simplest useful output, and inspect the response before running a batch. Check the final URL, status, content type, response size, source body, and whether the fields your workflow needs are actually present. If raw HTML contains the useful data, keep the request light. If the page is a thin shell, compare rendered output before writing selectors.

A good first test also separates page capture from parsing. Do not treat an empty parser result as proof that the target failed. First confirm whether the API response contains the content. Then decide whether the Python parser, the output format, the rendering choice, or the request profile needs to change.

First check What Python learns Next action
Final URL and status Whether the target resolved, redirected, failed, or returned a usable page Log this before parsing so failures stay diagnosable.
Raw HTML body Whether useful content exists without browser execution Use the lightest profile when source HTML is complete.
Rendered output Whether JavaScript changes the content Python receives Enable rendering only for templates that need it.
Response format Whether the downstream code needs markup, readable text, metadata, or visual proof Choose the format before building converters.
Parser result Whether selectors or extraction logic match the real page shape Fix parsing after capture evidence is known.

Which response format should Python request?

The best response format depends on the Python consumer. HTML is right when your parser needs DOM structure, selectors, attributes, tables, links, or embedded metadata. Text and Markdown are better when the workflow needs readable content for search, classification, summaries, RAG ingestion, or review. JSON metadata helps logging and diagnostics because it gives Python response evidence without forcing the parser to infer everything from the body. Screenshots and PDFs are useful when humans need visual proof for QA, monitoring, approvals, or archives.

This choice matters because Python makes it easy to build converters too early. A team can spend days transforming HTML into a shape that ScraperFly can already return. Test formats first, then write only the parsing and validation code that your product still needs.

For the full decision guide, use the web scraping API response formats page before locking a Python data model.

Python need Format to test Why it fits Trade-off to remember
Selectors, tables, links, attributes HTML or rendered HTML Preserves page structure for BeautifulSoup, lxml, or custom parsers Requires cleanup and target-specific extraction.
Search, summaries, lightweight analysis Text Compact output that is easy to store and compare Loses most DOM structure.
AI or RAG ingestion Markdown Keeps readable headings, links, and sections Not ideal when selectors or exact DOM relationships matter.
Logging and diagnostics JSON metadata Captures status, final URL, content type, size, and operational context Does not replace field extraction from the target content.
Review, monitoring, archive, proof Screenshot or PDF Shows what the rendered public page looked like to a human Heavier than machine-readable output.

When should Python enable rendering, sessions, headers, or routing?

Enable advanced controls when a specific target sample proves the simple request is not enough. JavaScript rendering is useful when source HTML does not contain the content that appears after the browser runs. Headers are useful when the public page expects legitimate request context such as language, accepted content type, or referer behavior. Sessions are useful when related requests depend on shared cookies or state. Country routing is useful when public content changes by region, language, currency, availability, or redirect path. Stronger routing is useful when repeated evidence shows the normal delivery path cannot retrieve a usable response.

Python makes it tempting to put every option into a reusable helper and forget why it exists. Resist that. Keep request profiles tied to page types. A static article page should not inherit the same profile as a JavaScript-heavy product grid or a regional availability page. This keeps latency, cost, and debugging under control.

Use the JavaScript rendering API guide for browser-built pages, the sessions API page for stateful workflows, the custom headers scraping API page for request context, and the rotating proxy scraping API page when delivery path matters.

How should Python handle scraping failures?

A Python scraping workflow should not retry every failure blindly. Some failures are configuration problems: malformed URLs, missing API keys, unsupported formats, invalid file output choices, or request options that do not match the target. Retrying those only burns time. Other failures are temporary or target-related: timeouts, rate limits, upstream 5xx responses, redirect loops, empty responses, oversized pages, or rendering timeouts. Those need controlled backoff, sample comparison, and clear logging.

The API response should tell Python what happened. Store the status, final URL, content type, response size, request profile, and retry history with the parsed result. That makes failures useful. If rendered output is empty, the team can compare source HTML, rendered HTML, screenshot state, wait timing, and target status before escalating. If rate limits appear, Python can slow the job instead of increasing pressure. If a target is blocked or region-specific, the workflow can test routing deliberately.

The error handling guidance below goes deeper, but the operating principle is simple: fix bad inputs, retry temporary conditions, and escalate only when the evidence supports it.

How can Python scraping jobs stay predictable as volume grows?

Predictability starts before the batch. Classify target pages by request weight: simple HTML, rendered HTML, headers or sessions, regional routing, premium delivery, screenshot, PDF, or combinations of those controls. Run small samples for each page type and log which profile actually works. Then scale with separate queues or job settings instead of treating every URL as the same kind of scrape.

This helps both engineering and billing. A one-off analysis can stay on pay-as-you-go credits. Recurring jobs can move to monthly credits when the pattern is clear. Expensive controls can be reserved for templates that prove they need them. Python remains responsible for job orchestration, limits, concurrency, storage, and alerts, while ScraperFly keeps page capture options explicit.

When planning volume, review pricing and use request evidence rather than assumptions. The cheapest reliable workflow is usually the one that keeps simple pages simple and upgrades only the pages that need more help.

What should Python own after ScraperFly captures the page?

Python should own the parts that are specific to your product: parsing fields, normalizing values, validating records, deduplicating results, storing data, feeding a queue, writing to a warehouse, triggering alerts, or preparing content for analytics and AI. ScraperFly should own the repeatable capture work around public pages: fetching, rendering when needed, response formats, sessions, headers, routing controls, and visual outputs.

This boundary keeps the system easier to maintain. If a parser breaks, the team can inspect the captured response and fix extraction logic. If the capture changes, the team can adjust the request profile without rewriting downstream Python code. If the project grows, the same response contract can move from a notebook into a scheduled job or production service.

Where should a Python team start?

Start in the API Builder or with a small terminal request. Prove one representative public URL, choose the response format, and compare raw and rendered capture before writing the full Python pipeline. Then move the proven request shape into Python with the HTTP client your team already uses.

Keep the first integration narrow: one target type, one format, clear logs, and a parser that checks for missing fields. Once that path is reliable, add batches, retries, queue behavior, storage, and monitoring. That gives the team a production path without turning the first Python script into a full scraping platform.

Python request path

Move from a proven ScraperFly request into Python without rebuilding capture infrastructure

Start with one working request, then use the same URL, format, rendering, routing, headers, and session choices in Python scripts, notebooks, queues, or data pipelines. Python keeps the business logic while ScraperFly keeps the public page capture layer stable.

PY
Python-ready

Call one API from the tools your team already uses

Use requests, httpx, notebooks, workers, or backend jobs to send the same proven ScraperFly request profile.

requestshttpxjobs
FMT
Output

Return the response shape Python can use immediately

Choose HTML for parsers, text or Markdown for readable content, JSON metadata for diagnostics, or screenshots and PDFs for visual proof.

htmlmarkdownjson
OPS
Operations

Keep capture controls visible as the workflow grows

Rendering, sessions, headers, country routing, waits, and stronger delivery can stay tied to the targets that actually need them.

rendersessionsrouting

Python request parameters worth proving first

url

The public page your Python workflow needs to capture.

format

HTML, text, Markdown, JSON metadata, screenshot, or PDF output.

render

Browser execution for pages that build useful content with JavaScript.

download

File output when screenshots or PDFs need to be stored by the Python job.

cURL example

Generate Markdown with the same request shape you can move into production

curl "https://scraperfly.com/api/v1?url=https%3A%2F%2Fexample.com&format=markdown" \
  -H "apikey: YOUR_API_KEY"

Before Python code

Validate target behavior before scaling scripts or notebooks

Python makes scraping automation easy to repeat, so the request profile needs to be right first. Check raw HTML, rendering needs, redirects, response size, headers, sessions, and output quality on samples.

Raw HTML response mapped to visible page data
01

Raw HTML availability

Check whether the fields you need are already present in the first HTML response.

Best first test for simple pages, articles, docs, listings, and product details.

Before and after JavaScript rendering comparison
02

JavaScript dependency

Compare raw HTML with the rendered DOM or screenshot before turning on browser rendering.

Use rendering when raw HTML is only a shell and scripts create the useful content.

Cookies, consent, session and access context for scraping
03

State & access context

Identify whether cookies, consent, login boundaries, pagination, or the same visitor state affect the response.

Use sessions and headers when continuity changes the data you receive.

Regional content variations across countries and routes
04

Geo/content variation

Test whether country, language, currency, inventory, SERP, ads, or route reputation changes the result.

Use geo or premium routing only when the target proves the response varies by route.

Checks before writing the Python workflow

Where is the target field?

Find whether the field exists in raw HTML, rendered DOM, an API call, structured data, a file, or a later interaction state.

What changes the response?

Sample a few URLs and compare status, final URL, content length, redirects, empty states, and visible result differences.

What context is required?

Mark any dependency on consent, locale, cookies, headers, authentication boundary, pagination, filters, or previous requests.

What does failure look like?

Define the signals for blocked, partial, stale, redirected, empty, timed-out, or region-mismatched responses before scaling.

How target evidence changes the Python request

Fetch mode

Raw HTML availability decides whether the first request can stay simple or needs rendering, waits, screenshots, or extraction.

Request context

State requirements decide whether to add headers, cookies, sessions, consent handling, or a stable visitor profile.

Routing choice

Geo and reputation findings decide whether standard routing is enough or a country/premium route is justified.

Validation rules

Known failure states become checks for retries, escalation, QA review, and deciding when a lighter profile is still complete.

Error handling

Turn scraping failures into fixes

Every web data workflow eventually meets a bad response: a missing URL, an invalid key, an empty HTML shell, a target 403, a rate limit, a render timeout, a broken PDF capture, or a JSON payload that does not contain the fields your product expected. ScraperFly is built to make those moments diagnosable. You inspect the HTTP status, the stable error code, the request profile, and the returned artifact, then choose the cheapest useful next move: fix the request, add credits, slow down, retry with backoff, enable rendering, change country, use premium routing, preserve headers, or validate the output before scaling.

Stable error shapeRetry decisionsCost-aware escalationOutput validation
Developer reviewing code and API request parameters on a laptop

01 / Request setup and access

Fix request mistakes first

Some failures are not target problems at all. They happen before ScraperFly can make a meaningful delivery attempt: a missing or malformed URL, an unsupported output format, an incompatible visual file type, a missing API key, an invalid key, or a key that has been paused or disabled. These errors are configuration signals, not retry signals: stop the workflow, point the developer to the exact field that needs correction, and keep credits focused on real target tests instead of repeated bad inputs.

missing_urlinvalid_urlunsupported_formatinvalid_api_key
  • Validate the URL and encoding before sending a batch.
  • Use supported outputs: HTML, text, Markdown, JSON, screenshot, or PDF.
  • Match screenshot file types to image output and PDF file type to PDF output.
  • Treat missing or invalid API keys as configuration work, not retry work.
Business dashboard with charts, documents and usage planning on a desk

02 / Credits, limits and concurrency

Separate limits from failures

A workload can fail because the account has no usable credits, the monthly plan limit has been reached, or concurrency is too aggressive for the current plan and target mix. ScraperFly makes those limits visible as operating signals, not mysterious scrape failures. That keeps the buying decision practical: start free, test the target, buy pay-as-you-go credits for uneven jobs, move to monthly credits when volume becomes predictable, and use backoff when request pressure is the real issue.

usage_limit_reachedrate_limitedcreditsbackoff
  • Use account status to check remaining credits before large runs.
  • Retry rate limits with backoff instead of immediately increasing pressure.
  • Keep one-off projects on pay-as-you-go when volume is uneven.
  • Move predictable recurring work to monthly credits when the pattern is proven.
Server room representing delivery paths, routing and network infrastructure

03 / Target delivery and network

Find delivery failures first

Many scraping platforms collapse delivery issues into a vague request failure. In production, that is not enough. The team needs to know whether the request timed out, the upstream target returned a temporary server error, the connection failed, the response was too large, redirects went somewhere unexpected, or the page came back as tiny HTML with no useful content. ScraperFly turns those failures into delivery evidence: try the light profile first, compare status and response size, then decide whether the next request needs backoff, another route, premium proxy, country targeting, or a narrower capture.

timeout5xxredirectsresponse_too_large
  • Retry temporary network and upstream failures with a controlled backoff policy.
  • Compare final URL, status, content type and response size across samples.
  • Escalate routing only when the response proves the simple path is unstable.
  • Treat oversized responses as a scope problem before scaling the same profile.
Digital security screen representing anti-bot and protected access signals

04 / Anti-bot, geo and access blocks

Read blocks before escalation

A target 403, 401, 429, CAPTCHA screen, WAF challenge, login wall, consent loop, or region-specific mismatch is not just an error; it is a clue about what the site expects from the visitor. Competitors often push teams toward a heavier default profile, but that can burn budget without proving the fix. ScraperFly's better path is evidence-based escalation: preserve realistic headers when context matters, use sessions when continuity changes the response, enable rendering when the useful content is browser-built, and choose premium or country routing when reputation or geography changes the result.

403429CAPTCHAcountry mismatch
  • Use premium routing when IP reputation is the proven bottleneck.
  • Use country targeting when language, currency, inventory or search results change by market.
  • Use headers, cookies and sessions when visitor state changes the response.
  • Reduce concurrency and add backoff when repeated requests trigger target throttling.
Developer preparing code and output artifacts on a laptop

05 / Rendering and output quality

Ship usable artifacts

A 200 status is not the same thing as a usable scrape. The raw HTML can be an empty app shell, Markdown can miss the main article, JSON can lack expected metadata, text can include noise, screenshots can be blank, and PDF or image output can fail if the browser step times out. ScraperFly is valuable because the same API request can move from raw HTML to rendered DOM, clean text, Markdown, JSON, screenshot or PDF, then be checked against the artifact your product actually needs. That reduces glue code, failed imports, and expensive batch runs that only discover bad output after the fact.

render_timeoutbrowser_render_failedJSON fieldsPDF/image output
  • Enable rendering when raw HTML is only a shell and the useful content appears after JavaScript.
  • Validate text, Markdown and JSON against expected fields before batching.
  • Use screenshot or PDF output when visual proof or audit evidence matters.
  • Treat blank or partial artifacts as quality failures even when HTTP status is successful.
ScraperFly fit

Cleaner error recovery

ScraperFly helps teams decide what to fix, what to retry, and what to escalate without turning every scrape into the most expensive request profile.

Stable error shape

Use HTTP status and error code together so application logic can choose between fixing input, refreshing credentials, slowing down, retrying, or escalating delivery.

Retry only when it helps

Network failures, rate limits, and temporary server errors can use backoff. Invalid URLs, unsupported formats, and bad keys should be corrected once.

Cost-aware escalation

Start with the light request profile, then add rendering, premium routing, country, sessions, headers, waits, or visual capture only when the failure proves it.

Validate output before scale

Confirm the real artifact your product needs: HTML, text, Markdown, JSON, screenshot, or PDF, before copying the same profile across a large URL set.

Batch discipline

Keep Python scraping runs affordable by proving the light profile first

Python jobs can scale quickly. Sample first, keep simple requests light, and reserve rendering, routing, sessions, or file outputs for the targets where they improve the result.

A lightweight HTML request returning a simple response
01

Basic fetch

Use a basic fetch when public HTML already contains the fields you need.

Lightest request profile; keep it when the response is complete.

JavaScript rendering producing a complete DOM
02

Rendering

Use rendering when raw HTML is a shell and JavaScript completes the page.

Heavier profile; use it only when browser output changes the result.

Several requests preserving cookies and visitor state
03

Stateful session

Use sessions when cookies, consent, locale, or pagination change the response.

Heavier state profile; preserve it only when continuity matters.

Request routing through geo and higher quality routes
04

Premium routing & geo

Use premium routing or geo only when origin, country, reputation, or regional content changes the result.

Heaviest routing profile; apply it only to targets that prove they need it.

What can make Python scraping jobs heavier

More infrastructure work

Browser rendering, routing choices, and longer waits mean the platform has to do more than return a simple response.

More target uncertainty

Redirects, empty states, rate limits, and challenge pages often require stronger delivery options or retries.

More state to preserve

Cookies, sessions, consent, and multi-page flows add moving parts that a plain stateless fetch does not have.

More evidence to return

Screenshots, PDFs, rendered output, and richer response artifacts are useful, but they are heavier than plain HTML.

How to keep batch cost predictable

Sample before scale

Test a small URL set first and group targets by the lightest profile that returns complete data.

Do not render by default

Inspect raw HTML before turning on rendering. Many public pages already contain the data you need.

Escalate by evidence

Move up only when the response shows missing content, state dependency, geo variance, or routing problems.

Measure useful results

Optimize around valid records delivered, not raw request volume. A lighter profile is best only when it stays complete.

Python questions

Common questions about Python web scraping with ScraperFly

Practical answers for teams using Python to capture public pages, choose response formats, decide when rendering is needed, and keep scraping jobs easy to operate.

Python FAQ
Requests

Calling ScraperFly from Python

Use a normal HTTP client and keep the capture profile explicit.

Can I call ScraperFly from Python requests or httpx?

Yes. Python can call ScraperFly like any hosted API, then process the returned HTML, text, Markdown, metadata, screenshot, or PDF in your own code.

Should I start in Python or the API Builder?

Start with the API Builder or a small terminal request when possible. Once the response is proven, move the same request profile into Python.

Output

Choosing response formats

Pick the format around the Python consumer, not habit.

Which output format is best for Python parsing?

Use HTML or rendered HTML when selectors, links, tables, or attributes matter. Use text or Markdown when the workflow needs readable content.

Can Python workflows request screenshots or PDFs?

Yes. Screenshots and PDFs are useful when the workflow needs visual proof, QA review, archive records, or human approval.

Rendering

Handling JavaScript pages

Rendering should solve a proven content gap.

When should a Python request enable rendering?

Enable rendering when source HTML misses content that appears after browser execution. Keep static pages on lighter source capture.

Do sessions and headers matter in Python scraping?

They can. Use headers for legitimate request context and sessions when related public requests depend on shared cookies or state.

Operations

Running jobs in production

Python should own the pipeline around a proven capture layer.

Does ScraperFly replace Python parsing and storage?

No. ScraperFly captures public page responses and output formats. Python still owns extraction, validation, storage, scheduling, and downstream analysis.

How should Python retry failed scraping requests?

Fix bad inputs instead of retrying them. Retry temporary limits, network errors, and upstream failures with bounded backoff and clear logs.