# BrowserFabric

Python SDK for **BrowserFabric** — cloud browser automation API with persistent sessions and CDP access.

## Install

```bash
pip install browserfabric
```

## Quick Start

```python
import browserfabric
import asyncio

async def main():
    async with browserfabric.browser() as session:
        await session.navigate("https://example.com")
        await session.click("a")
        await session.screenshot("result.png")

asyncio.run(main())
```

## Authentication

Set your API key as an environment variable or pass it directly:

```python
# Via environment variable
export BROWSERFABRIC_API_KEY=bf_your_key_here

# Or pass directly
async with browserfabric.browser(api_key="bf_...") as session:
    ...
```

## Persistent Sessions

Save and restore browser state (cookies, localStorage) across sessions:

```python
# Save state on close
async with browserfabric.browser(persist=True) as session:
    await session.navigate("https://app.example.com/login")
    await session.type("#email", "user@example.com")
    await session.type("#password", "secret")
    await session.click("#submit")
    ctx = await session.save_context("my-app-login")

# Restore later
async with browserfabric.browser(context_id=ctx["context_id"]) as session:
    # Already logged in
    await session.navigate("https://app.example.com/dashboard")
```

## CDP WebSocket

Connect with Playwright directly for full browser control:

```python
from playwright.async_api import async_playwright

# Get the CDP WebSocket URL from session info
info = await session.session_info()
ws_url = info["ws_url"]

# Connect with Playwright
pw = await async_playwright().start()
browser = await pw.chromium.connect_over_cdp(ws_url)
page = browser.contexts[0].pages[0]
await page.goto("https://example.com")
```

## Available Methods

| Method | Description |
|--------|-------------|
| `navigate(url)` | Go to a URL |
| `click(selector)` | Click an element |
| `type(selector, text)` | Type into an input |
| `find(selector)` | Find elements |
| `screenshot(filename)` | Take a screenshot |
| `observe()` | Get interactive DOM elements |
| `snapshot()` | Get accessibility tree |
| `page_info()` | Get page URL and title |
| `session_info()` | Get session metadata + CDP URL |
| `save_context(name)` | Save browser state |
| `close()` | Close the session |

## Self-Hosted

Point to your own BrowserFabric instance:

```python
async with browserfabric.browser(base_url="http://your-server:9000") as session:
    ...
```

## License

MIT
