自动化 API
先通过本地 HTTP API 启动 VirtualBrowser 环境,再用 Playwright 连接返回的 CDP 端口。复用环境现有上下文,保留其配置与代理,不要额外启动独立 Chromium。
专业版功能
需登录有效专业版会员,从客户端 API 页面复制实际地址和 api-key。下方端口 9000 与环境 ID 1 仅为示例。
安装依赖
bash
python -m pip install requests playwright本示例连接 VirtualBrowser 内核,无需再运行 playwright install 下载另一份 Chromium。
Python 完整示例
python
import requests
from playwright.sync_api import sync_playwright
BASE_URL = "http://127.0.0.1:9000" # Replace with the client API address
PROFILE_ID = 1 # Replace with an existing profile ID
session = requests.Session()
session.headers.update({"api-key": "YOUR_API_KEY"})
def call_api(endpoint, body):
response = session.post(
f"{BASE_URL}{endpoint}", json=body, timeout=(5, 60)
)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict) or payload.get("success") is not True:
raise RuntimeError(payload)
return payload
launch = call_api("/api/launchBrowser", {"id": PROFILE_ID})
try:
port = launch.get("data", {}).get("debuggingPort")
if not isinstance(port, int) or isinstance(port, bool) or not 0 < port < 65536:
raise RuntimeError(f"Missing or invalid data.debuggingPort: {launch}")
with sync_playwright() as p:
browser = p.chromium.connect_over_cdp(f"http://127.0.0.1:{port}")
if not browser.contexts:
raise RuntimeError("No profile context returned by CDP")
context = browser.contexts[0]
page = context.new_page()
page.goto("https://example.com", wait_until="domcontentloaded")
print(page.title())
finally:
try:
print(call_api("/api/stopBrowser", {"id": PROFILE_ID}))
finally:
session.close()关键说明
- 环境 ID 从 环境列表 读取,不要假定 ID 固定。
- 启动响应的端口位于 data.debuggingPort,不是顶层字段。
- 页面操作失败时也会在 finally 中尝试关闭环境。
- 启动超时后先查运行列表,再决定是否重试。
- 本地 API 服务端口与浏览器 CDP 调试端口是两个端口。
- Node.js 和 Puppeteer 接入见 Playwright 接入指南。



