Python / TypeScript / Go SDK
The official BrowserPilot SDKs mirror Playwright's ergonomics (launch → newPage → locator / getByRole), while driving the desktop BrowserPilot window you are already signed in to. Cookies, saved credentials and isolated environments stay intact — your code and you share the exact same live session.
Installation
pip install browserpilotnpm install browserpilot-sdkgo get github.com/xy200303/browserpilot/sdk/go@latest30-Second Quickstart
from browserpilot import launch
with launch() as bp:
page = bp.new_page(env="env-default")
page.goto("https://github.com/topics/browser-automation")
page.locator("article").wait_for(timeout=15)
print("Cards matched:", page.count("article"))
# PNG bytes with an APCA-adaptive 100px coordinate grid
png_bytes = page.screenshot()
page.unlock()import { launch } from 'browserpilot-sdk'
const bp = await launch()
try {
const page = await bp.newPage({ env: 'env-default' })
await page.goto('https://github.com/topics/browser-automation')
await page.locator('article').waitFor({ timeout: 15 })
console.log('Cards matched:', await page.count('article'))
const pngBytes = await page.screenshot()
await page.unlock()
} finally {
await bp.close()
}package main
import (
"context"
"fmt"
"time"
"github.com/xy200303/browserpilot/sdk/go"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
bp, err := browserpilot.Launch(ctx)
if err != nil {
panic(err)
}
defer bp.Close()
page, err := bp.NewPage(ctx)
if err != nil {
panic(err)
}
_ = page.Goto(ctx, "https://github.com/topics/browser-automation")
count, _ := page.Count(ctx, "article")
fmt.Println("Cards matched:", count)
_ = page.Unlock(ctx)
}Local & Remote Modes over /api/*
/mcp stays strictly dedicated to MCP protocol clients; all three SDKs and the CLI talk uniformly over /api/*:
- Local Auto-Discovery (Default): With no connection arguments,
launch()andconnect()read your localmcp.jsonand call/api/*on127.0.0.1(bypassing system proxies automatically, and auto-launching BrowserPilot onlaunch()if closed). - Remote HTTP Mode: Pass
apiandtoken(or setBROWSERPILOT_API+BROWSERPILOT_TOKEN) to drive a remote BrowserPilot server over HTTP/HTTPS/api/*+ Bearer Token without ever spawning a local process:
from browserpilot import launch
with launch(api="https://bp.example.com/api", token="YOUR_TOKEN") as bp:
page = bp.new_page()
page.goto("https://example.com")import { launch } from 'browserpilot-sdk'
const bp = await launch({
api: 'https://bp.example.com/api',
token: process.env.BROWSERPILOT_TOKEN
})bp, err := browserpilot.Launch(
ctx,
browserpilot.WithRemote("https://bp.example.com/api", os.Getenv("BROWSERPILOT_TOKEN")),
)Local Discovery Order
In default local mode, launch() prefers your existing desktop installation so your logins stay intact:
BROWSERPILOT_EXEenvironment variable: explicit executable path (useful in CI or portable setups).- Running local instance: reads
mcp.jsonand probes/api/tools. If BrowserPilot is already open, the SDK attaches directly without spawning a second process. - Standard desktop install paths:
%LOCALAPPDATA%\Programs\BrowserPilot\on Windows,/Applications/BrowserPilot.appon macOS,/opt/BrowserPilot/on Linux. - SDK cache & on-demand archive: on clean machines where none of the above exist, downloads the matching
v<version>archive into~/.browserpilot/sdk/<version>/and verifies its SHA-256 digest (BROWSERPILOT_OFFLINE=1disables network downloads).
Safe Cleanup Semantics
Desktop processes launched by the SDK run detached so a script crash never kills your browser. Calling bp.close() only closes environments opened during that SDK session.
Playwright Concept Mapping
All timeout, poll and delay values use seconds in Python and TypeScript, and time.Duration in Go:
| Playwright | BrowserPilot SDK |
|---|---|
browser.newContext() | bp.environment(id) / bp.api.envs.create(...) (isolated partition + window) |
context.newPage() | bp.newPage({ env }) / env.newPage() (globally unique tab-... id) |
page.goto(url) | page.goto(url) (waits for load completion) |
page.getByRole / getByText / getByLabel | Same methods; enforces strict single-element match instead of silently clicking the first |
locator.fill(text) | Focus → Select All → Paste replacement (passing "" clears existing input) |
locator.type(text) | Appends keystrokes at the current cursor |
page.frameLocator(sel) | page.frameLocator(sel) (works across cross-origin OOPIFs) |
page.waitForResponse(url) | page.waitForResponse(urlOrRegex) (arms capture before waiting so early requests are never missed) |
context.cookies() / addCookies() | page.cookies() / page.addCookies() / page.clearCookies() (isolated per environment) |
Advanced Patterns
1. Event Streams & Network Waiting
Subscribing to response or request automatically enables reference-counted CDP capture (net_start) and tears it down when the last listener unsubscribes or page.close() is called:
off = page.on("response", lambda ev: print(ev.payload["status"], ev.payload["url"]))
page.get_by_role("button", name="Refresh").click()
res = page.wait_for_response("/api/items", timeout=10)
off()2. Cross-Origin iframes
Use frame_locator to resolve an <iframe>'s URL fragment and interact inside cross-origin frames cleanly:
frame = page.frame_locator("iframe#checkout-widget")
frame.get_by_placeholder("Verification code").fill("849201")
frame.locator("button.submit").click()3. Live Per-Environment Proxy & Fingerprint Settings
Update proxy rules, User-Agent, locale, timezone and WebRTC policy for a specific environment without restarting:
await bp.api.network.set({
env: 'env-store-us',
proxy: { mode: 'fixed', rules: 'http://127.0.0.1:7890' },
timezone: 'America/New_York',
acceptLanguages: 'en-US,en',
webrtcPolicy: 'disable_non_proxied_udp'
})4. Dialog Policies, Human Handoff & Raw CDP
# Accept the next confirm dialog instead of the default cancel policy
page.accept_dialog(once=True)
page.get_by_role("button", name="Delete").click()
# Lift the overlay and prompt the user to finish 2FA or SMS verification
page.handoff("Please complete SMS verification to continue")
# Send single or batched Chrome DevTools Protocol commands
metrics = page.cdp("Page.getLayoutMetrics")5. Virtual-Scroll Doc Extraction, In-Browser Fetch & Scoped Downloads
Built-in helpers for virtualized online docs/sheets (Tencent Docs, Feishu/Lark, Notion), CSRF-safe multipart uploads, redacted XHR debugging, and concurrency-safe downloads:
# 1) Harvest full Markdown & tables from virtual-scroll or canvas docs
doc = page.extract_doc(save_path="/tmp/spec.md")
# 2) Upload a local archive from inside the browser's authenticated session (zero cookie exposure)
resp = page.fetch(
"https://developer.example.com/api/submit",
multipart_files=[{"field": "file", "local_path": "/tmp/submit.zip"}],
form={"taskId": "1001"},
)
# 3) Inspect recent XHR/Fetch traffic with auth headers automatically redacted
logs = page.net_log(filter="submit", status="error")
# 4) Bind the next download on this tab to an exact path with MD5/SHA-256 verification
with page.expect_download("/tmp/report.xlsx") as dl:
page.get_by_role("button", name="Export").click()
print(dl.value["path"], dl.value["md5"])6. Calling All 105 Built-in Tools
Reach workflows, Geetest captcha solvers, media extraction and more via bp.api.* or bp.call(tool, args):
result = bp.api.workflow.run("GitHub digest", inputs={"topic": "browser-automation"})
solved = bp.call("captcha_solve", {"tabId": page.tab_id, "engine": "auto"})Next Steps
- Understand environments, tabs, workflows and control states in Core Concepts
- Try ready-to-run automation examples in Copyable Recipes