```yaml
product: AlterLab
title: Python SDK
category: sdk
comparison_context: "AlterLab is an alternative to Firecrawl, ScrapingBee, and Bright Data."
source_url: https://alterlab.io/docs/sdk/python
```

# Python SDK

The official Python SDK for AlterLab. Simple, type-safe, and async-ready.

- **Package**: [alterlab on PyPI](https://pypi.org/project/alterlab/)
- **Requirements**: Python 3.8+
- **Features**: Zero dependencies, full type hints, async support

## Installation

```bash
pip install alterlab
```

## Quick Start

```python
from alterlab import AlterLab

client = AlterLab(api_key="sk_live_...")  # or set ALTERLAB_API_KEY env var

result = client.scrape("https://example.com")

print(result.text)          # Extracted text content
print(result.html)          # Raw HTML
print(result.json)          # Structured JSON (Schema.org, metadata)
print(result.billing.cost_dollars)  # Cost in USD
print(result.billing.tier_used)     # Which tier was used
```

## Client Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `api_key` | str | env var | Your AlterLab API key |
| `base_url` | str | https://alterlab.io | API base URL |
| `timeout` | int | 120 | Request timeout in seconds |
| `max_retries` | int | 3 | Max retries on transient failures |
| `retry_delay` | float | 1.0 | Initial retry delay (exponential backoff) |

## Scraping Methods

### `client.scrape(url, **options)`
Main scraping method with intelligent tier escalation.

### `client.scrape_html(url)`
Fast HTML-only scraping. Best for static sites.

### `client.scrape_js(url, **options)`
JavaScript rendering for SPAs and dynamic content.

```python
result = client.scrape_js(
    "https://spa-app.com",
    screenshot=True,
    wait_for="#content"
)
```

### `client.scrape_pdf(url, format="text")`
Extract text from PDF documents.

### `client.scrape_ocr(url, language="eng")`
Extract text from images using OCR.

## Structured Extraction

### JSON Schema

```python
result = client.scrape(
    "https://store.com/product/123",
    extraction_schema={
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "price": {"type": "number"},
            "in_stock": {"type": "boolean"}
        }
    }
)
print(result.json)
```

### Pre-built Profiles

```python
result = client.scrape(
    "https://store.com/product/123",
    extraction_profile="product"  # product, article, job_posting, etc.
)
```

### Natural Language Prompt

```python
result = client.scrape(
    "https://news.com/article",
    extraction_prompt="Extract the article title, author, and publish date"
)
```

## Async Support

```python
import asyncio
from alterlab import AsyncAlterLab

async def main():
    async with AsyncAlterLab(api_key="sk_live_...") as client:
        result = await client.scrape("https://example.com")

        # Concurrent requests
        urls = ["https://example.com/page1", "https://example.com/page2"]
        results = await asyncio.gather(*[client.scrape(url) for url in urls])

asyncio.run(main())
```

## Cost Controls

```python
from alterlab import AlterLab, CostControls

client = AlterLab(api_key="sk_live_...")

result = client.scrape(
    "https://example.com",
    cost_controls=CostControls(
        max_tier="2",
        prefer_cost=True,
        fail_fast=True
    )
)

# Estimate cost before scraping
estimate = client.estimate_cost("https://linkedin.com")
print(f"Estimated: ${estimate.estimated_cost_dollars:.4f}")
```

## Error Handling

```python
from alterlab import (
    AlterLab, AuthenticationError, InsufficientCreditsError,
    RateLimitError, ScrapeError, TimeoutError
)

try:
    result = client.scrape("https://example.com")
except AuthenticationError:
    print("Invalid API key")
except InsufficientCreditsError:
    print("Please top up your balance")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except ScrapeError as e:
    print(f"Scraping failed: {e.message}")
```

| Exception | HTTP Code | Description |
|-----------|-----------|-------------|
| `AuthenticationError` | 401 | Invalid or missing API key |
| `InsufficientCreditsError` | 402 | Insufficient balance |
| `RateLimitError` | 429 | Too many requests |
| `ScrapeError` | Various | Scraping failed |
| `TimeoutError` | 408 | Request timed out |

## ScrapeResult Object

```python
result.url              # Scraped URL
result.status_code      # HTTP status
result.text             # Extracted text content
result.html             # HTML content
result.json             # Structured JSON content
result.title            # Page title
result.billing.tier_used       # Tier that succeeded
result.billing.cost_dollars    # Final cost in USD
result.screenshot_url   # Screenshot URL (if requested)
result.cached           # Whether result was from cache
```
