Skip to main content

ghostcrawl — Python SDK

The official Python client for the GhostCrawl API. Collect web data at scale — scrape, crawl, search, extract structured data, manage browser sessions, and automate the full data-collection pipeline.

Install

The current release is 2.3.9 (ghostcrawl==2.3.9):

pip install ghostcrawl==2.3.9

Requires Python 3.11+. Runtime dependencies: httpx>=0.28.1.

Managed cloud or self-host

The client talks to the GhostCrawl API. With a cloud API key it points at https://api.ghostcrawl.io — no Docker, browsers, or local runtime required. If you prefer to run the service yourself, follow https://docs.ghostcrawl.io/self-host and point the client at your local base URL.

The default client is synchronous — no await, no asyncio.run. Every method returns a typed result directly. Prefer async? Import AsyncGhostCrawl for the awaitable twin (see Async below).

Quickstart

from ghostcrawl import GhostCrawl

# Reads GHOSTCRAWL_API_KEY from environment, or pass token= explicitly
client = GhostCrawl(token="gck_live_YOUR_KEY")

# Scrape a URL — returns a typed ScrapeResult
result = client.scrape(url="https://example.com", format="markdown")
print(result.markdown)

# Start a crawl and wait for it to finish in one call. The server blocks until
# the run is terminal (completed/failed/cancelled) or the timeout elapses —
# no client-side poll loop.
run = client.crawl(
    url="https://example.com", max_depth=2, max_pages=50,
    wait=True, wait_timeout=300,
)
print(run["run_id"], run["status"])

# Web search — pass wait=True and the SDK blocks until results are ready,
# then hands you a typed SearchResult (no hand-rolled poll).
results = client.search(query="latest AI research", wait=True)
for r in results.results:
    print(r["title"], r["url"])

result is a typed ScrapeResult — read result.markdown, result.html, result.status_code, or result.url. Every field is also dict-accessible (result["markdown"]) if you prefer.

Authentication

import os
from ghostcrawl import GhostCrawl

# Option 1: pass token directly
client = GhostCrawl(token="gck_live_YOUR_KEY")

# Option 2: set environment variable (recommended for production)
os.environ["GHOSTCRAWL_API_KEY"] = "gck_live_YOUR_KEY"
client = GhostCrawl()

Every request sends Authorization: Bearer <token> by default. The API also accepts the same account key in an X-Api-Key header (set it as a custom header); if both are present, Authorization wins. See the authentication guide for details.

Extract structured data

from ghostcrawl import GhostCrawl

client = GhostCrawl(token="gck_live_YOUR_KEY")

# Define a schema and extract matching data
data = client.extract(
    url="https://example.com/product",
    schema={
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "price": {"type": "number"},
            "description": {"type": "string"},
        },
    },
)
print(data["name"], data["price"])

Browser utilities — content, screenshot, PDF

from ghostcrawl import GhostCrawl

client = GhostCrawl(token="gck_live_YOUR_KEY")

# Rendered content as a JSON envelope: {url, status, format, status_code, content, bytes}
page = client.content(url="https://example.com", engine="auto")
print(page["status_code"], page["bytes"], "bytes")
print(page["content"][:200])

# Screenshot — returns raw PNG bytes you can write straight to disk
png = client.screenshot(url="https://example.com", full_page=True)
with open("page.png", "wb") as f:
    f.write(png)

# PDF — returns raw application/pdf bytes (any engine; the PDF-capable engine is selected automatically, so a Firefox/WebKit
# identity still receives real PDF bytes)
pdf = client.pdf(url="https://example.com", paper_format="a4")
with open("page.pdf", "wb") as f:
    f.write(pdf)

Agent (BYO model, account-gated)

The agent lane runs a natural-language browser task. It is bring-your-own-model — you supply your own LLM provider via provider_config — and account-gated: the API replies 404 not_found unless the capability is enabled for your account. agent() does not raise on that 404; it returns the problem+json body so you branch on "detail" in result.

from ghostcrawl import GhostCrawl

# provider_config is BYO — reference your provider key by ENV-VAR NAME only,
# never a literal key in committed code.
client = GhostCrawl(
    token="gck_live_YOUR_KEY",
    provider_config={
        "provider": "openai",
        "api_key": "OPENAI_API_KEY",   # resolved from env by the caller
        "model": "gpt-4o",
    },
)
result = client.agent(
    url="https://books.toscrape.com",
    instruction="click the 'Books to Scrape' link",
)
if "detail" in result:
    print(f"agent lane not enabled for this account: {result['detail']}")
else:
    print(result)

The interactive MCP lane (navigate / act / observe) is available in the Python and Node SDKs only — see ghostcrawl.mcp.wrapper.GhostCrawlMCPClient. That wrapper is an optional MIT client (pip install ghostcrawl[mcp]) that lets your AI agent talk to GhostCrawl's proprietary MCP endpoint: managed cloud (https://mcp.ghostcrawl.io) or the MCP server inside the self-host Docker image (http://localhost:47700/mcp). GhostCrawl does not host an AI model on cloud or self-host today. There is no public, standalone MCP server package.

Browser sessions

from ghostcrawl import GhostCrawl

client = GhostCrawl(token="gck_live_YOUR_KEY")

# Create a session
session = client.sessions.create(profile_name="my-profile")
session_id = session["session_id"]

# Extend and release
client.sessions.extend(session_id, duration_seconds=600)
client.sessions.release(session_id)

Error handling

from ghostcrawl import GhostCrawl, AuthenticationError, RateLimitError, APIError

client = GhostCrawl(token="gck_live_YOUR_KEY")

try:
    result = client.scrape(url="https://example.com")
except AuthenticationError:
    print("Invalid API key — check your token")
except RateLimitError:
    print("Rate limit reached — retry after a short delay")
except APIError as e:
    print(f"Server error: {e.status_code}")

Closing the client

The client cleans itself up when it goes out of scope, but you can close it explicitly (or use it as a context manager) to release the HTTP connection deterministically:

from ghostcrawl import GhostCrawl

with GhostCrawl(token="gck_live_YOUR_KEY") as client:
    result = client.scrape(url="https://example.com")
    print(result.markdown)
# HTTP connection is closed automatically on block exit

Async twin

Prefer async/await? Import AsyncGhostCrawl — the genuine awaitable twin. Every method is a coroutine and the client supports async with:

import asyncio
from ghostcrawl import AsyncGhostCrawl

async def main():
    async with AsyncGhostCrawl(token="gck_live_YOUR_KEY") as client:
        result = await client.scrape(url="https://example.com", format="markdown")
        print(result.markdown)

asyncio.run(main())

Both clients are real: GhostCrawl is the synchronous default, AsyncGhostCrawl is the awaitable twin. Pick whichever matches your program — they share the same method names, parameters, and typed results.

All resources

Resource Client attribute Key operations
Scraping client.scrape(url=…) Render and return page content
Web search client.search(query=…, wait=True) Search Google, Bing, DuckDuckGo
Data extraction client.extract(url=…, schema=…) Structured JSON from any page
Deep crawl client.crawl(url=…) Crawl a site depth-first
URL map client.map(url=…) Discover all reachable URLs
Content client.content(url=…) Rendered content JSON envelope
Screenshot client.screenshot(url=…) Capture a URL to PNG bytes
PDF client.pdf(url=…) Render a URL to PDF bytes (any engine)
Agent (BYO) client.agent(url=…, instruction=…) NL browser task — account-gated, BYO model
Crawl runs client.crawl_runs start (wait=True), wait, list, get, cancel
Sessions client.sessions create, extend, release
Profiles client.profiles list, get, create, update, delete
Webhooks client.webhooks list, get, create, delete, rotate-secret
Schedules client.schedules list, get, create, delete
Datasets client.datasets list, get, create, delete, append rows
Recordings client.recordings list, get, delete
Key-Value Store client.kv get, set, delete

LangChain integration

pip install ghostcrawl-langchain
from ghostcrawl_langchain import GhostCrawlScrapeTool, GhostCrawlSearchTool

scrape_tool = GhostCrawlScrapeTool()
search_tool = GhostCrawlSearchTool()

Self-hosted

from ghostcrawl import GhostCrawl

client = GhostCrawl(
    token="gck_live_YOUR_KEY",
    base_url="http://localhost:8080",  # your self-hosted instance
)

Account & session persona

me() returns your account profile — including max_concurrency, the number of sessions your plan may run at once. usage() reports the current billing window. session_persona(session_id) returns a running session's customer-safe persona: a display-only whitelist of device_class, os_class, browser_class, and locale (never any raw or internal detail).

me = client.me()
print(me["max_concurrency"])                 # concurrent-session ceiling for your plan

persona = client.session_persona(session_id)
print(persona["device_class"], persona["os_class"],
      persona["browser_class"], persona["locale"])

License

MIT — see LICENSE.

Metadata

Release files for ghostcrawl 2.3.91

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

Source distribution (sdist)

Source distribution for ghostcrawl 2.3.91
File Size Uploaded Provenance Actions
ghostcrawl-2.3.91.tar.gz 171.6 kB Without provenance Details for ghostcrawl-2.3.91.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ghostcrawl 2.3.91
File Interpreter ABI Platform Actions
ghostcrawl-2.3.91-py3-none-any.whl Python 3 none any Details for ghostcrawl-2.3.91-py3-none-any.whl

Total release size: 697.2 kB

Release files / ghostcrawl-2.3.91.tar.gz

Download URL ghostcrawl-2.3.91.tar.gz
Size 171.6 kB
Tags Source
SHA-256 checksum
How to use checksums
0d20e4218c18144ace9ee23c3bf268eae58bf0475fa4d7d16a805f7ce683ea54
BLAKE2b-256 checksum
How to use checksums
c961ff8ecb8f6ababc8fb63bc9644338c6d975e675290b6fcf82be4f47d10f35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / ghostcrawl-2.3.91-py3-none-any.whl

Download URL ghostcrawl-2.3.91-py3-none-any.whl
Size 525.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
450a7dcbb88d492cd38529982bc8fe64639f802e00a7ba5935fe5d921d0c84be
BLAKE2b-256 checksum
How to use checksums
9c5f053748abc26c3cd3d121bd9ad97772bb539f80db0ca91fc082293d7a3052
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for ghostcrawl 2.3.91

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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