# browserless-bap

> Python async and sync SDK for Browserless's Browser Automation Protocol.

## Key resources

- README: https://github.com/browserless/bap-py#readme
- Browserless documentation: https://docs.browserless.io
- GraphQL schema: `src/browserless_bap/mutations.graphql`

## Logging

Use the Python logger `browserless_bap` for SDK diagnostics and its child
`browserless_bap.websockets` for WebSocket frame logs. Setting the parent to
`DEBUG` enables child frame logs too.

```python
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("browserless_bap").setLevel(logging.DEBUG)
```

The `browserless_bap.websockets` logger redacts tokens and `Authorization` header
values. Frame logs can still contain page content and other application data;
review them before sharing.

## Timeouts

All timeout values are milliseconds; the default per-step `timeout` is `30000`.
Mutations with server-side timeouts get `5000` ms of client headroom once.
`connect_timeout` defaults to `timeout`, bounds the entire WebSocket dial
(including setup and handshake), and is disabled by values of `0` or less.
Connection timeouts raise the SDK's `browserless_bap.BAPTimeoutError` with
`operation == "connect"`.

A connect deadline expiring is terminal for that page's connection; create a
new page to retry. These rules apply to both async and sync APIs. Live URL
completion waits have their own timeout behavior, described below.

## API methods

<!-- AUTOGEN:method-list START -->

Generated Page methods: `add_cookies`, `add_script_tag`, `add_style_tag`, `authenticate`, `check`, `click`, `close`, `close_live_url`, `content`, `cookies`, `emulate_media`, `eval_on_selector`, `eval_on_selector_all`, `evaluate`, `fulfill`, `go_back`, `go_forward`, `goto`, `hover`, `html`, `live_url`, `load_secret`, `map_selector`, `markdown`, `pdf`, `preferences`, `proxy`, `query_selector`, `query_selector_all`, `reconnect`, `reject`, `reload`, `request`, `response`, `screenshot`, `scroll`, `select_option`, `send`, `set_content`, `set_extra_http_headers`, `set_java_script_enabled`, `set_user_agent`, `set_viewport_size`, `solve`, `solve_image_captcha`, `stop_session_recording`, `switch_to_window`, `text`, `title`, `type`, `uncheck`, `url`, `wait_for_event`, `wait_for_function`, `wait_for_live_complete`, `wait_for_navigation`, `wait_for_network_idle`, `wait_for_request`, `wait_for_response`, `wait_for_selector`, `wait_for_timeout`, `watch_event`

<!-- AUTOGEN:method-list END -->

## Response keys and optional fields

Options and keyword arguments use `snake_case`; returned dictionaries keep the
server's field names (`liveURLId`, `httpOnly`, `childElementCount`), as Playwright
for Python does for cookies.

`query_selector()` and `query_selector_all()` fetch element HTML only with
`html=True`, including element-scoped queries. Reading `inner_html` or
`outer_html` without requesting it raises `BAPValueError` with a fix hint.
`response()` omits bodies unless `body=True` or `body_encoding=True` (which implies
the body and adds `base64Encoded`).

`eval_on_selector()` returns text; `eval_on_selector_all()` returns element
details. Unlike Playwright's methods, neither accepts a page function.
SDK errors are `BAPTimeoutError`, `BAPConnectionError` and `BAPValueError`, still
subclassing the matching builtins; the builtin-named SDK exports are removed.

## Live URL handoffs

```python
link = await page.live_url(instructions="Sign in, then click Done.", timeout=120_000)
print(link["liveURL"])
completion = await page.wait_for_live_complete(timeout=120_000)
if completion["reason"] != "userDone":
    raise RuntimeError(f"Handoff ended: {completion['reason']}")
# To cancel a link instead: await page.close_live_url(link["liveURLId"])
```

The sync facade uses the same calls without `await`.

For a richer human handoff, pass an instructions card:

```python
link = await page.live_url(
    instructions={
        "layout": "panel",
        "format": "markdown",
        "title": "Complete sign in",
        "summary": "**Sign in** to continue.",
        "steps": ["Open your inbox", "Enter the code"],
        "currentStep": 2,
    },
    done_label="Continue",
    fail_label="Need help",
    requester_name="Support",
)
```

With string instructions, use the top-level `instructions_title`, `steps`,
`current_step` and `instructions_format`. With a card, put `title`, `steps`,
`currentStep` and `format` inside it. Button labels and `requester_name` always
stay top-level. The server validates card limits. For an explicitly annotated
card, import `LiveURLInstructions` from `browserless_bap.types`.

The SDK subscribes before minting and retains completion until the next mint,
so a quick completion is not lost between `live_url()` and `wait_for_live_complete()`.
Wait timeouts are in milliseconds and raise `BAPTimeoutError`. By default
there is no client wait deadline; pass a positive timeout to bound the wait.
`timeout=0` also disables the wait deadline. Timing out or cancelling a wait does
not close the live URL.

Completion reasons are `userDone`, `userFailed`, `timeout`, `closed`, and
`viewerDisconnected`. Only `userDone` explicitly means the person finished.
Use `close_live_url(id)` to end a link programmatically;
the response contains `liveURLId`. Await each mint before starting another one.
A re-mint starts a new wait even when the server reuses its ID; existing waits
remain associated with the preceding handoff. Closing the page or losing the
connection rejects pending waits. The completion subscription closes when no pending handoffs or public listeners
remain; cached results remain available. Public listeners use `on`/`off`.
For reused IDs, the server emits the preceding handoff’s completion before the
replacement’s completion on the same ordered subscription stream.

Live URL handoffs need a Browserless server that supports
`wait_for_live_complete()` (the `liveComplete` event), `close_live_url()` and
instruction cards. When a live URL call passes `instructions`, this client sends
them in the newer format, which older servers reject even for a plain string.
Older clients send a format that newer servers reject. Upgrading is
therefore a coordinated client/server cutover, not a rolling server-first
upgrade.

For self-hosted upgrades, pause new handoffs and drain active ones, upgrade the
server and all clients together, then verify mint, completion, and close before
resuming handoffs. Handoffs remain unavailable during this cutover. To roll back,
pause and drain again and restore both the previous server and previous clients;
rolling back only one side leaves an incompatible pair. No mixed-version
compatibility path is provided by this SDK.
