Metadata-Version: 2.5
Name: crawlen
Version: 0.1.0
Summary: Official Python SDK for the Crawlen API: search, scrape, parse, map and crawl the web, and find people and companies.
Project-URL: Homepage, https://www.screenshotrender.com
License-Expression: MIT
Keywords: ai agents,crawlen,crawler,llm,markdown,search,web scraping
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.25
Description-Content-Type: text/markdown

# Crawlen for Python

The official Python SDK for the [Crawlen](https://www.screenshotrender.com) API: search the web, scrape any page to Markdown, parse documents, map and crawl whole sites, and find people and companies.

```bash
pip install crawlen
```

Python 3.9 or later. A sync client, `Crawlen`, and an asyncio one, `AsyncCrawlen`, with the same methods.

## Quick start

```python
from crawlen import Crawlen

crawlen = Crawlen(api_key="YOUR_API_KEY")  # or set CRAWLEN_API_KEY

page = crawlen.scrape("https://example.com")
print(page.markdown)
```

## Endpoints

```python
# Search the web, and read every result too
results = crawlen.search("open source vector databases", limit=5, scrape_options={"formats": ["markdown"]})
for result in results.web or []:
    print(result.title, result.url)

# One page, in any formats
page = crawlen.scrape(
    "https://stripe.com/pricing",
    formats=["markdown", {"type": "json", "prompt": "The plan names and their monthly prices"}],
)

# A document: a public URL, a file path, bytes or an open file
paper = crawlen.parse("https://arxiv.org/pdf/1706.03762")
report = crawlen.parse("report.pdf")

# Every URL on a site
site = crawlen.map("https://nextjs.org", limit=100)

# A whole site: starts the crawl, waits for it, returns every page
crawl = crawlen.crawl(
    "https://nextjs.org/docs",
    limit=8,
    on_progress=lambda job: print(f"{job.completed} of {job.total} pages"),
)
print([doc.metadata.source_url for doc in crawl.data])

# A person, a list of people or a company, researched and sourced (2 to 4 minutes)
found = crawlen.find("Linear (linear.app)", type="company", on_progress=lambda job: print(job.message or job.status))
print(found.data[0])
```

Options are keyword arguments in snake_case (`only_main_content`, `max_age`, `scrape_options`), sent as the API's camelCase. Options the SDK doesn't list are passed through too, in either form. Values you pass (headers, JSON schemas, browser actions) are sent untouched. A Pydantic model works as a JSON schema:

```python
from pydantic import BaseModel

class Plans(BaseModel):
    names: list[str]

page = crawlen.scrape("https://stripe.com/pricing", formats=[{"type": "json", "schema": Plans}])
print(page.json)
```

## Results

Results are plain dicts, so they print, serialize and compare as dicts. Their fields also read as attributes, under the API's name or in snake_case: `doc.metadata.source_url` is `doc["metadata"]["sourceURL"]`. A documented field that wasn't returned reads as `None`.

## Jobs without waiting

`crawl()` and `find()` wait for you. To start a job and come back later:

```python
job = crawlen.start_crawl("https://nextjs.org/docs", limit=50)

crawlen.get_crawl_status(job.id)  # status, counters, pages so far
crawlen.get_crawl_errors(job.id)  # pages that failed, robots.txt blocks
crawlen.cancel_crawl(job.id)      # True if it stopped it

# Find works the same way: start_find, get_find_status, cancel_find
```

`get_crawl_status` collects every page of a large crawl's results. Pass `auto_paginate=False` for one page at a time, or limit it with `max_pages`, `max_results` or `max_wait_time` (seconds). When pages are left out, `next` says where to continue.

| Waiting option | Default | |
|---|---|---|
| `poll_interval` | crawl 2 s, find 5 s | Seconds between status checks |
| `timeout` | none | Seconds to wait before a `JobTimeoutError`. The job keeps running. |
| `on_progress` | | Called with the job after every check (it may be async with `AsyncCrawlen`) |

Interrupting the wait (Ctrl+C, or cancelling the task with `AsyncCrawlen`) cancels the job too.

## Async

```python
import asyncio
from crawlen import AsyncCrawlen

async def main():
    async with AsyncCrawlen() as crawlen:
        pages = await asyncio.gather(*(crawlen.scrape(url) for url in ["https://a.dev", "https://b.dev"]))

asyncio.run(main())
```

## Errors

Every failure is a `CrawlenError` with the HTTP `status`, the API's `code` and, for invalid requests, the `field`:

```python
from crawlen import CrawlenError, JobTimeoutError

try:
    crawlen.scrape("https://example.com")
except CrawlenError as err:
    print(err.status, err.code, err)  # 402 insufficient_credits ...
```

Common codes: `invalid_api_key`, `invalid_request`, `insufficient_credits`, `busy`, `not_found`, `blocked`, `timeout`. A `JobTimeoutError` (code `job_timeout`) carries the `job_id` to check later.

## Retries and timeouts

Requests are retried (2 times by default, with backoff) only when that can't do paid work twice: when the API is busy or briefly unavailable, when it asks to wait (`Retry-After`), and for network failures on reads. A scrape that may have run is never sent again.

## Configuration

```python
Crawlen(
    api_key="YOUR_API_KEY",  # default: CRAWLEN_API_KEY
    api_url="https://...",   # default: CRAWLEN_API_URL, then the hosted API
    timeout=300.0,           # seconds per HTTP request
    max_retries=2,
    backoff_factor=0.5,      # seconds before the first retry, doubling after
    http_client=None,        # your own httpx.Client (proxies, custom transports)
)
```

Per call, every method also takes `request_timeout` (seconds). Use the client as a context manager, or call `close()`, to release its connections.
