Skip to main content

SDKs

Python SDK

kloakd-sdk for Python — one API for everything, full module coverage with async support

8 min read


Install

pip install "kloakd-sdk>=0.7.0"

Python 3.9+ | version 0.7.0 | httpx transport

Client

from kloakd import Kloakd

client = Kloakd(
    api_key="sk-live-...",
    organization_id="your-org-uuid",
    timeout=100.0,  # seconds (the default); keep it above the API's 85 s hand-off
    max_retries=3,
)

Quickstart — one call does everything

result = client.crawl(
    "https://example.com",
    max_pages=50,
    extract_schema={"title": "css:h1", "content": "css:article"},
)

for page in result.pages:
    if page.ok:
        print(f"{page.url} → {page.structured_data}")

That's it. crawl() internally:

  1. Discovers all pages on the site (Webgrph BFS)
  2. Fetches each page through the anti-bot engine, which works out per site what it takes (a browser, a residential exit, a challenge solver) — no force_browser needed
  3. Extracts structured data from each page if extract_schema is provided (Kolektr, using cached fetch artifacts — no second HTTP round-trip)

Per-page failures are caught and marked success=False — the crawl never aborts on a single page error.

Primary method

client.crawl()

result = client.crawl(
    "https://example.com",
    max_depth=3,
    max_pages=100,
    extract_schema={"title": "css:h1", "price": "css:.price"},
    include_external_links=False,
    session_artifact_id=None,  # reuse a Fetchyr session for login-protected sites
)

print(f"Discovered: {result.total_pages_discovered} pages")
print(f"Fetched:    {result.pages_fetched}")
print(f"Failed:     {result.pages_failed}")

for page in result.pages:
    if page.ok:
        print(f"  {page.url} {page.structured_data}")
    else:
        print(f"  {page.url} FAILED: {page.error}")

Parameters

| Parameter | Type | Default | Description | |---|---|---|---| | url | str | required | Seed URL to start crawling from | | max_depth | int | your plan's maximum | Maximum BFS depth (sent only when given) | | max_pages | int | your plan's maximum | Maximum pages to crawl (sent only when given) | | extract_schema | dict[str, str] | None | CSS selector schema for structured extraction | | include_external_links | bool | False | Follow off-domain links | | session_artifact_id | str | None | Reuse an authenticated session artifact (from Fetchyr) |

Returns: SiteCrawlResult

| Field | Type | Description | |---|---|---| | success | bool | Whether the crawl completed | | url | str | Seed URL | | total_pages_discovered | int | Pages found during BFS | | pages_fetched | int | Pages successfully fetched | | pages_failed | int | Pages that failed (included with success=False) | | pages | list[CrawlPage] | All pages with HTML and optional structured data | | crawl_artifact_id | str | Artifact ID for the site hierarchy | | error | str | Error message if crawl failed entirely | | crawl_id | str | The crawl's id | | crawl_status | str | The crawl's own status, including held_quota | | held | bool | The crawl is held for quota (below) | | message | str | The API's note on the crawl's state, such as why it is held |

client.crawl_stream() — async streaming

For long-running crawls, use the async streaming version to receive real-time progress events:

import asyncio
from kloakd import AsyncKloakd

client = AsyncKloakd(api_key="sk-live-...", organization_id="...")

async def main():
    async for event in client.crawl_stream(
        "https://example.com",
        max_pages=500,
        extract_schema={"title": "css:h1"},
    ):
        if event.type == "page_fetched":
            print(f"[{event.page}/{event.total}] {event.url} OK")
        elif event.type == "page_failed":
            print(f"[{event.page}/{event.total}] {event.url} FAIL: {event.error}")
        elif event.type == "crawl_complete":
            result = event.metadata["result"]
            print(f"Done: {result.pages_fetched} fetched, {result.pages_failed} failed")

asyncio.run(main())

Or use the sync client's generator:

from kloakd import Kloakd

client = Kloakd(api_key="sk-live-...", organization_id="...")

for event in client.crawl_stream("https://example.com", max_pages=500):
    if event.type == "page_fetched":
        print(f"[{event.page}/{event.total}] {event.url} OK")
    elif event.type == "crawl_complete":
        print("Done!")

Event types

| Type | Description | |---|---| | discovery_started | Crawl discovery has begun | | discovery_complete | Discovery finished, fetch phase starting | | page_fetching | About to fetch page N of total | | page_fetched | Page fetched successfully | | page_failed | Page fetch failed (crawl continues) | | crawl_complete | All pages processed, final summary in metadata["result"] |

Low-level methods

Need fine-grained control? The individual modules are still available:

evadr.fetch()

page = client.evadr.fetch("https://example.com")   # follows a 202 hand-off to the result
print(f"Status: {page.status_code}")
print(f"Artifact ID: {page.artifact_id}")

webgrph.crawl()

crawl = client.webgrph.crawl(      # waits for the crawl; start_crawl() returns at once
    "https://example.com",
    max_depth=3,
    max_pages=100,
)
print(f"{crawl.crawl_id}: {crawl.total_pages} pages")

kolektr.page()

result = client.kolektr.page(
    "https://example.com",
    schema={"title": "css:h1", "price": "css:.price"},
)
for record in result.records:
    print(record)

One record per item

On a list page, give the repeated element as item_selector in a full spec; each match is one record, with the field selectors read inside it (rules):

result = client.kolektr.page(
    "https://books.toscrape.com/",
    schema={
        "item_selector": "article.product_pod",
        "fields": [
            {"name": "title", "selector": "h3 a", "attribute": "title"},
            {"name": "price", "selector": "p.price_color"},
        ],
    },
)
print(result.total_records)   # 20: one record per book

A full spec (a dict with a fields list) is sent as given, so this works with 0.5.0 and is documented for 0.6.0. Without item_selector the page is one record.

Artifact chaining

Pass artifact IDs between low-level methods to skip redundant work:

page = client.evadr.fetch("https://example.com")

data = client.kolektr.page(
    "https://example.com",
    schema={"title": "css:h1"},
    fetch_artifact_id=page.artifact_id,
)

Error handling

from kloakd.errors import (
    AuthenticationError, KloakdError, PaymentRequiredError, QuotaExceededError, RateLimitError,
)

try:
    result = client.crawl("https://example.com")
except AuthenticationError:
    print("Invalid API key")
except (PaymentRequiredError, QuotaExceededError) as e:
    print(f"Billing: {e} — {e.upgrade_url}")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except KloakdError as e:
    print(f"Error: {e}")

Advanced namespaces

client.skanyr     # Site store: resources, APIs, snapshots
client.nexus      # Strategy engine
client.parlyr     # Natural language queries
client.fetchyr    # Logins & authenticated scraping

Crawls: held, partial, continue

A crawl whose organisation ran out of allowance is held (held_quota), not failed, and resumes by itself. webgrph.crawl and webgrph.wait_for_crawl return it at once with held True, success False and message the server's text. client.crawl returns SiteCrawlResult.held with crawl_id, crawl_status and message.

A crawl that stopped early ends completed with is_partial True. CrawlResult also has partial_reason, resumable, pages_discovered, pages_fetched, pages_unfetched and error_code.

crawl = client.webgrph.crawl("https://example.com")
if crawl.held:
    print(crawl.message)                       # held for quota; it resumes by itself
elif crawl.resumable:
    client.webgrph.continue_crawl(crawl.crawl_id)   # ApiError 409 when it cannot be continued
    crawl = client.webgrph.wait_for_crawl(crawl.crawl_id, url="https://example.com")
print(crawl.is_partial, crawl.pages_fetched, crawl.pages_unfetched)

Each PageNode has fetch_status and fetch_error.

Login sessions

login = client.fetchyr.start_login_session("https://example.com/login")
print(login.status, login.next, login.session_artifact_id)

status = client.fetchyr.get_session(login.session_artifact_id)   # once the login has a session
print(status.status, status.pause_reason)
client.fetchyr.resume_session(status.artifact_id)   # ApiError 409 when the session is not paused

start_login_session(target_url, method=None, cookies=None, user_agent=None, country=None) returns a LoginSession; get_session and resume_session return a SessionStatus. The flow is described under logins.

Batch jobs

batch = client.create_batch_job(
    ["https://books.toscrape.com/catalogue/page-1.html",
     "https://books.toscrape.com/catalogue/page-2.html"],
    entity_type="products",
    fields=["title", "price"],
)
batch = client.get_batch_job(batch.id)
print(batch.status, batch.completed_items, batch.total_items)

client.pause_batch_job(batch.id)
client.resume_batch_job(batch.id)
client.cancel_batch_job(batch.id)

page = client.list_batch_jobs(page=1, page_size=20)          # page.total, page.batch_jobs
results = client.get_batch_job_results(batch.id, limit=100, offset=0)
for item in results.results:
    print(item.url, item.status, item.extracted_data)

saved = client.download_batch_job(batch.id, "batch.csv", format="csv")
print(saved.path, saved.bytes)

create_batch_job(urls, extraction_config=None, crawl_id=None, entity_type=None, fields=None) returns a BatchJob (id, name, status, total_items, completed_items, created_at, message). A control the batch's state does not allow raises ApiError with status_code 409 and code invalid_batch_transition. A create or resume that could not be queued raises ApiError 503 with code dispatch_failed and is not retried. The limit on batches at once raises ConcurrencyLimitError; its active_crawls holds the API's active_batches. The rules are on the batch jobs page.

Unified scrape

scrape = client.unified_scrape(
    "https://books.toscrape.com/",
    prompt="extract all book titles and prices",
)
if scrape.status == "failed":          # success is True even then: check status
    print("the scrape failed")
elif scrape.auth_required:
    print("login needed:", scrape.discovery_id)
else:
    job = client.get_unified_scrape(scrape.job_id)
    print(job.status, job.result)

unified_scrape(url, prompt=None, mode=None, schema=None, options=None, context=None, constraints=None, session_artifact_id=None) follows a 202 hand-off and returns a UnifiedScrapeResult. Each entry of escalation_path has from_level, to_level, reason and timestamp. See unified scrape for the failed and login answers.

Crawl-extract jobs and exports

webgrph has start_crawl_extract, crawl_extract, get_crawl_extract, wait_for_crawl_extract, get_crawl_extract_results, iter_crawl_extract_results, crawl_extract_all_results, get_crawl_extract_pages, export_crawl_extract, download_crawl_extract and cancel_crawl_extract for the crawl-extract job.

An export (ExportDownload, SavedExport) has a crawl object read from the response's X-Crawl-* headers: status, is_partial, partial_reason, pages_discovered, pages_fetched, pages_unfetched, cancelled and root_unfetched. For a batch export crawl and job_status are None.

Changes in 0.7.0

  • max_depth and max_pages are sent only when you give them (client.crawl, crawl_stream, webgrph.crawl). Left out, the crawl runs to your plan's limits; 0.6.0 sent 3 and 100.
  • PageNode.status_code and PageNode.crawl_parent_url: the API sends neither.
  • ExtractionResult.has_more and total: use total_records. ExtractionResult gains level, level_reason and login_options.
  • nexus.execute and nexus.knowledge, and error on the Nexus results: a failed call raises.

Next steps

Was this page helpful?