Skip to main content

Python client for the browsercli browser workspace daemon

Project description

browsercli Python Client

Zero-dependency Python client for the browsercli browser workspace daemon.

Installation

pip install -e clients/python   # from the repo root

Platform Support

The client auto-detects the RPC transport from the session file:

  • macOS / Linux — connects via Unix socket (socket_path in session.json)
  • Windows — connects via TCP localhost (rpc_port in session.json)

No code changes are needed — BrowserCLI.connect() handles both transports.

Quick Start

from browsercli import BrowserCLI

# Connect to a running daemon
# macOS/Linux: reads ~/.browsercli/session.json
# Windows: reads %LOCALAPPDATA%\browsercli\session.json
ac = BrowserCLI.connect()

# Navigate and inspect
ac.goto("/")
title = ac.dom_query("h1", mode="text")
print(f"Title: {title}")

# Evaluate JavaScript
result = ac.eval("1 + 1")
print(f"Result: {result}")

# Screenshot
ac.screenshot(out="page.png")

# Stop the daemon
ac.stop()

Error Handling

All exceptions inherit from BrowserCLIError, so you can catch the whole family or handle specific cases:

from browsercli import (
    BrowserCLI,
    BrowserCLIError,
    ConnectionError,
    AuthenticationError,
    SessionError,
    NotFoundError,
    ServerError,
)

try:
    ac = BrowserCLI.connect()
    ac.dom_query("#missing-element", mode="text")
except SessionError:
    print("Daemon not running — start it with: browsercli start")
except ConnectionError:
    print("Cannot reach daemon — is the socket file valid?")
except AuthenticationError:
    print("Token rejected — daemon may have restarted, reconnect")
except NotFoundError as e:
    print(f"Element or endpoint not found: {e}")
except ServerError as e:
    print(f"Daemon internal error (HTTP {e.status_code}): {e.error_message}")
except BrowserCLIError as e:
    print(f"Unexpected client error: {e}")

Exception Hierarchy

BrowserCLIError            # Base — catch-all
├── SessionError            # session.json missing/invalid
├── ConnectionError         # RPC endpoint unreachable (socket or TCP)
├── AuthenticationError     # HTTP 401 (bad token)
└── RPCError                # Any HTTP 4xx/5xx with status_code + error_message
    ├── BadRequestError     # HTTP 400
    ├── NotFoundError       # HTTP 404
    └── ServerError         # HTTP 5xx

Constructor

BrowserCLI(socket_path="", token="", timeout=30.0, *, rpc_port=0)
Parameter Type Description
socket_path str Unix socket path (macOS/Linux). Mutually exclusive with rpc_port.
token str Bearer token for daemon authentication
timeout float Request timeout in seconds (default 30.0)
rpc_port int TCP port on localhost (Windows). Keyword-only.

You must provide either socket_path or rpc_port. In most cases, use the connect() factory instead of calling the constructor directly.

API Reference

Method Description
BrowserCLI.connect(session_path=None, timeout=30.0) Create client from session file (auto-detects Unix socket or TCP)
status() Daemon and browser status
version() RPC and schema version info
goto(url) Navigate to a path or URL
eval(expression) Evaluate JavaScript
reload() Reload the page
dom_query(selector, mode) Query a single DOM element
dom_all(selector, mode) Query all matching elements
dom_attr(selector, name) Get an element attribute
dom_click(selector) Click an element
dom_type(selector, text, clear) Type text into an input
dom_wait(selector, state, timeout_ms) Wait for element state
screenshot(selector, out) Capture screenshot (PNG bytes)
console(level, limit, clear) Fetch console entries
network(limit, clear) Fetch network log entries
perf() Page performance metrics
stop() Stop the daemon
plugin_list() List installed plugins
plugin_rpc(rpc_path, body=None) Call a custom plugin RPC endpoint (/x/...)

Valid Parameter Values

Parameter Valid Values Default
dom_query / dom_all mode "outer_html", "text" "outer_html"
dom_wait state "visible", "hidden", "attached", "detached" "visible"
console level "" (all), "log", "warn", "error", "info" ""

Invalid values raise ValueError before any RPC call is made.

Logging

The client uses Python's logging module under the logger name browsercli:

import logging
logging.basicConfig(level=logging.DEBUG)
# Now all RPC requests and responses are logged.

Running Tests

cd clients/python
python -m unittest tests.test_client -v

Tests include:

  • Session parsing: valid/invalid/missing session files (including rpc_port for Windows)
  • Parameter validation: client-side checks for all method arguments
  • Contract tests: mock server (Unix socket on macOS/Linux, TCP on Windows) emulating the Rust daemon
  • Error handling: auth failures, 400/404/500 errors, connection errors
  • Exception hierarchy: inheritance and attribute verification

Requirements

  • Python 3.9+
  • A running browsercli daemon (browsercli start)
  • No external dependencies (stdlib only)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

browsercli-1.0.4.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

browsercli-1.0.4-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file browsercli-1.0.4.tar.gz.

File metadata

  • Download URL: browsercli-1.0.4.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for browsercli-1.0.4.tar.gz
Algorithm Hash digest
SHA256 f103e8947d9c4336cdbe8c872f3a5821e37472bb2bb53c2b2769297e53cf5e8e
MD5 2b737b25a2d3da639ca8280d221744d2
BLAKE2b-256 007c572bee4d46a32ea4cae5778005dca748a817884496dfedf5ebb8f81262bb

See more details on using hashes here.

File details

Details for the file browsercli-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: browsercli-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 10.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for browsercli-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 acee7749bdf40fff25d4ee543e37d4b9228b08095b0812785332e26853d620ff
MD5 64ae53bbc1f248d6c4b9552ce4c9e498
BLAKE2b-256 f81c34b8340311981a170c3b26fb8ee09485f680b45659fc6386c267b4ab0fc8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page