Skip to main content

webscraping_ai

PyPI CI

Official Python client for the WebScraping.AI API — web scraping with Chromium JavaScript rendering, rotating datacenter/residential/stealth proxies, and AI-powered question answering and structured field extraction on any page. Sync and async clients included. See the API documentation for the full parameter reference.

4.0 is a hard break from 3.x. See CHANGELOG.md for the migration notes. If you cannot update your call sites yet, stay on webscraping_ai == 3.2.1.

Install

pip install webscraping_ai

Requires Python 3.9 or newer.

Quick start

Sign up to get an API key — the free trial includes 2,000 credits, no credit card required. Your key lives in the dashboard.

from webscraping_ai import Client

client = Client(api_key="YOUR_API_KEY")

# Page HTML
html = client.html("https://example.com")

# Visible text, optionally as a structured JSON response
text = client.text("https://example.com", text_format="json", return_links=True)

# CSS-selected HTML
heading = client.selected("https://example.com", selector="h1")
multiple = client.selected_multiple("https://example.com", selectors=["h1", "p"])

# LLM-powered helpers
answer = client.question("https://example.com", question="What is the page title?")
fields = client.fields(
    "https://example.com",
    fields={"title": "Main product title", "price": "Current product price"},
)

# Google search results (SERP) for a query
results = client.serp("coffee machines", gl="us", hl="en", page=1)

# Account quota
info = client.account()

The client is also a context manager, which closes the underlying connection pool on exit:

with Client(api_key="...") as client:
    client.html("https://example.com")

Async usage

AsyncClient mirrors Client but uses async def methods backed by httpx.AsyncClient:

import asyncio
from webscraping_ai import AsyncClient

async def main():
    async with AsyncClient(api_key="YOUR_API_KEY") as client:
        html = await client.html("https://example.com")
        print(html)

asyncio.run(main())

Error handling

Every non-2xx response is mapped to a typed exception so you can except on the situation you actually care about rather than parsing status codes:

from webscraping_ai import (
    Client,
    AuthenticationError,
    RateLimitError,
    PaymentRequiredError,
    APITimeoutError,
    APIConnectionError,
)

client = Client(api_key="YOUR_API_KEY")

try:
    client.html("https://example.com")
except AuthenticationError:
    ...  # 403 — wrong or missing API key
except PaymentRequiredError:
    ...  # 402 — out of credits
except RateLimitError:
    ...  # 429 — too many concurrent requests
except APITimeoutError:
    ...  # request did not complete in time
except APIConnectionError:
    ...  # transport-level failure

All exceptions inherit from WebScrapingAIError, so you can catch everything the client raises with a single except if you prefer. API errors expose the parsed error envelope (message, status, status_code, status_message, body, response_body).

APITimeoutError and APIConnectionError are raised without chaining the underlying httpx exception (it holds the request URL, which contains your API key); the original exception type is named in the message instead.

Logging and your API key

The API key travels in the query string, and httpx logs every request URL at INFO on the httpx logger. Importing webscraping_ai installs a logging.Filter on that logger that rewrites api_key=<value> to api_key=[REDACTED], so enabling INFO logging does not leak the key. The filter only covers the httpx logger; if you log request URLs yourself, redact them too.

Endpoint reference

Method HTTP route Returns
client.html(...) GET /html str (page HTML)
client.text(...) GET /text str or dict (JSON)
client.selected(...) GET /selected str
client.selected_multiple(...) GET /selected-multiple list
client.question(...) GET /ai/question str
client.fields(...) GET /ai/fields dict (wrapped under result)
client.serp(...) GET /serp dict (SerpResult)
client.account() GET /account dict

Every page-fetch method accepts the full set of API parameters as keyword arguments: headers, timeout, js, js_timeout, wait_for, proxy, country, custom_proxy, device, error_on_404, error_on_redirect, js_script, plus the per-endpoint extras (return_script_result, format, text_format, return_links, selector, selectors, question, fields). See the API documentation for the full parameter reference.

SERP

client.serp(q, *, engine=None, gl=None, hl=None, page=None) returns parsed search engine results for a query. It is query-shaped rather than URL-shaped, so none of the page-fetch parameters above apply. Flat 15 credits per search; failed searches are not charged. Raises ValueError before any request when q is not a non-blank str or page is not an int >= 1 (the server also rejects it with a 400, not billed; checking client-side saves the round trip). q is sent as given.

Parameter Type Default Description
q str — Search query (required)
engine str "google" Search engine; currently only google
gl str "us" Two-letter country code for the search
hl str "en" Two-letter language code for the results
page int 1 Results page number (10 per page); 1–100, server rejects > 100 with a 400
results = client.serp("coffee machines", gl="gb", page=2)
print(results["search_information"]["organic_results_state"])  # "Results for exact spelling"
for r in results["organic_results"]:
    print(r["position"], r["title"], r["link"])
print(results["pagination"])  # {"current": 2, "next": 3}

The response dict has search_parameters (engine, q, gl, hl, page), search_information (query_displayed, organic_results_state, optional showing_results_for and total_results), organic_results (position — 1-based within the page — title, link, domain, displayed_link, optional snippet and date), optional related_searches (query), and pagination (current, optional next). Optional keys are absent when the engine does not show them, so use .get() for those.

API response-shape notes

Two endpoints return shapes that differ from the OpenAPI spec examples. The client returns the raw response unchanged, so:

  • /ai/fields wraps the extracted fields under a result key: {"result": {"title": "...", "price": "..."}}.
  • /selected-multiple returns list[list[str]], not a flat list[str].

Development

mise install                    # or use python 3.13 from any source
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest
ruff check .
mypy src/webscraping_ai

Smoke testing

bin/smoke.py hits every endpoint once against the live API through the sync Client, plus one account call through AsyncClient. It puts src/ first on sys.path, so it always tests the working tree (you still need the runtime deps, e.g. from pip install -e ".[dev]"). It is not part of the pytest suite and costs ~32 credits per run: the four page calls run with js=False and proxy="datacenter" (1 credit each), question and fields cost 6 each, and the SERP call is 15. Each case checks the result shape, not just that no exception was raised (SERP must return organic results for the query sent, selected_multiple must match something, and so on), and FAIL lines redact the API key.

WEBSCRAPING_AI_API_KEY=... python bin/smoke.py

Each call prints an ok or FAIL line (any exception counts as a failure, and the sweep continues); the script exits non-zero if any call fails.

License

MIT.

Release files for webscraping-ai 4.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for webscraping-ai 4.1.0
File Size Uploaded
webscraping_ai-4.1.0.tar.gz 18.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for webscraping-ai 4.1.0
File Interpreter ABI Platform
webscraping_ai-4.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 36.6 kB

Release files / webscraping_ai-4.1.0.tar.gz

Download URL webscraping_ai-4.1.0.tar.gz
Size 18.9 kB
Tags Source
SHA-256 checksum
How to use checksums
e000049fb11d0d171204cd7e5b0942b99671b3fe4628d97538f5f3f134d6be9b
BLAKE2b-256 checksum
How to use checksums
1cbfabb8eda74472d7edf2971f87d5abcd873e126c6e0e3b9df40a1da32684f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release files / webscraping_ai-4.1.0-py3-none-any.whl

Download URL webscraping_ai-4.1.0-py3-none-any.whl
Size 17.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7c3e1c7ca0a1b3adcb9fc0713a67180614001ef726a6113fd5e0c1d394a979b3
BLAKE2b-256 checksum
How to use checksums
713585ae0131ac999cd054445f30ce15411cb37d6045190fa8a169413a2acf46
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 25, 2026.

Transparency log

Release history Release notifications | RSS feed

4.2.0

2 release files

This release

4.1.0 This release

2 release files

4.0.1

2 release files

4.0.0

2 release files

3.2.1

2 release files

3.2.0

2 release files

3.1.3

2 release files

3.1.2

2 release files

2.0.2

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page