browserpilot-sdk 0.19.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- browserpilot/__init__.py +71 -0
- browserpilot/client.py +317 -0
- browserpilot/errors.py +48 -0
- browserpilot/install.py +263 -0
- browserpilot/locator.py +270 -0
- browserpilot/page.py +406 -0
- browserpilot/paths.py +125 -0
- browserpilot/transport.py +253 -0
- browserpilot_sdk-0.19.0.dist-info/METADATA +189 -0
- browserpilot_sdk-0.19.0.dist-info/RECORD +12 -0
- browserpilot_sdk-0.19.0.dist-info/WHEEL +5 -0
- browserpilot_sdk-0.19.0.dist-info/top_level.txt +1 -0
browserpilot/paths.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""端点文件和安装位置。
|
|
2
|
+
|
|
3
|
+
App 在启动时把 userData 固定成「系统配置目录/BrowserPilot」,
|
|
4
|
+
所以 mcp.json 的位置只跟系统有关,跟 App 装在哪儿无关。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ntpath
|
|
10
|
+
import os
|
|
11
|
+
import posixpath
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
'app_data_root',
|
|
17
|
+
'mcp_file',
|
|
18
|
+
'data_home',
|
|
19
|
+
'sdk_dir',
|
|
20
|
+
'downloads_dir',
|
|
21
|
+
'looks_like_app',
|
|
22
|
+
'install_candidates',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _get(env, name):
|
|
27
|
+
"""读环境变量。Windows 上 os.environ 的键大小写不敏感,这里统一处理。"""
|
|
28
|
+
if name in env:
|
|
29
|
+
return env[name]
|
|
30
|
+
lowered = name.lower()
|
|
31
|
+
for key, value in env.items():
|
|
32
|
+
if key.lower() == lowered:
|
|
33
|
+
return value
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _join(platform, *parts):
|
|
38
|
+
# 模拟别的系统时用那个系统的分隔符,报错信息和测试都更直观。
|
|
39
|
+
return ntpath.join(*parts) if platform == 'win32' else posixpath.join(*parts)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _home():
|
|
43
|
+
return str(Path.home())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def app_data_root(platform=None, env=None):
|
|
47
|
+
"""App 的 userData 根目录。"""
|
|
48
|
+
platform = platform or sys.platform
|
|
49
|
+
env = os.environ if env is None else env
|
|
50
|
+
if platform == 'win32':
|
|
51
|
+
return _get(env, 'APPDATA') or _join(platform, _home(), 'AppData', 'Roaming')
|
|
52
|
+
if platform == 'darwin':
|
|
53
|
+
return _join(platform, _home(), 'Library', 'Application Support')
|
|
54
|
+
return _get(env, 'XDG_CONFIG_HOME') or _join(platform, _home(), '.config')
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def mcp_file(platform=None, env=None):
|
|
58
|
+
"""`%APPDATA%\\BrowserPilot\\mcp.json` / `~/Library/Application Support/...` / `~/.config/...`"""
|
|
59
|
+
return _join(platform or sys.platform, app_data_root(platform, env), 'BrowserPilot', 'mcp.json')
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def data_home(env=None):
|
|
63
|
+
"""SDK 自己的目录:下载缓存和便携副本都放这儿。"""
|
|
64
|
+
env = os.environ if env is None else env
|
|
65
|
+
return _get(env, 'BROWSERPILOT_HOME') or os.path.join(_home(), '.browserpilot')
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def sdk_dir(version):
|
|
69
|
+
return os.path.join(data_home(), 'sdk', version)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def downloads_dir():
|
|
73
|
+
return os.path.join(data_home(), 'downloads')
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def looks_like_app(path, platform=None):
|
|
77
|
+
"""确认某个路径真是应用本体,而不是同目录下的 cli/browserpilot。
|
|
78
|
+
|
|
79
|
+
打包后的 App 一定有 `resources/app.asar`;AppImage 是一整个大文件。
|
|
80
|
+
"""
|
|
81
|
+
platform = platform or sys.platform
|
|
82
|
+
candidate = Path(path)
|
|
83
|
+
try:
|
|
84
|
+
if not candidate.is_file():
|
|
85
|
+
return False
|
|
86
|
+
if platform == 'darwin' and '.app/Contents/MacOS/' in str(candidate).replace('\\', '/'):
|
|
87
|
+
return True
|
|
88
|
+
if candidate.stat().st_size > 20 * 1024 * 1024:
|
|
89
|
+
return True
|
|
90
|
+
return (candidate.parent / 'resources' / 'app.asar').is_file()
|
|
91
|
+
except OSError:
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _from_path(exe, platform, env):
|
|
96
|
+
"""安装包会把 CLI 放进 PATH;同一个目录里通常就是应用本体。"""
|
|
97
|
+
raw = _get(env, 'PATH') or ''
|
|
98
|
+
separator = ';' if platform == 'win32' else ':'
|
|
99
|
+
return [_join(platform, directory, exe) for directory in raw.split(separator) if directory]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def install_candidates(platform=None, env=None):
|
|
103
|
+
"""桌面版的默认安装位置。SDK 优先用这些,因为登录态都在用户日常那份里。"""
|
|
104
|
+
platform = platform or sys.platform
|
|
105
|
+
env = os.environ if env is None else env
|
|
106
|
+
if platform == 'win32':
|
|
107
|
+
local = _get(env, 'LOCALAPPDATA') or _join(platform, _home(), 'AppData', 'Local')
|
|
108
|
+
pf = _get(env, 'ProgramFiles') or 'C:\\Program Files'
|
|
109
|
+
pf86 = _get(env, 'ProgramFiles(x86)') or 'C:\\Program Files (x86)'
|
|
110
|
+
return [
|
|
111
|
+
_join(platform, local, 'Programs', 'BrowserPilot', 'BrowserPilot.exe'),
|
|
112
|
+
_join(platform, pf, 'BrowserPilot', 'BrowserPilot.exe'),
|
|
113
|
+
_join(platform, pf86, 'BrowserPilot', 'BrowserPilot.exe'),
|
|
114
|
+
*_from_path('BrowserPilot.exe', platform, env),
|
|
115
|
+
]
|
|
116
|
+
if platform == 'darwin':
|
|
117
|
+
return [
|
|
118
|
+
'/Applications/BrowserPilot.app/Contents/MacOS/BrowserPilot',
|
|
119
|
+
_join(platform, _home(), 'Applications', 'BrowserPilot.app', 'Contents', 'MacOS', 'BrowserPilot'),
|
|
120
|
+
]
|
|
121
|
+
return [
|
|
122
|
+
'/opt/BrowserPilot/BrowserPilot',
|
|
123
|
+
'/usr/lib/browserpilot/BrowserPilot',
|
|
124
|
+
*_from_path('BrowserPilot', platform, env),
|
|
125
|
+
]
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""程序面 `/api/*` 的 HTTP 通道。
|
|
2
|
+
|
|
3
|
+
三条必须照做的约定:
|
|
4
|
+
1. 端点文件里的 `api` 字段是程序面地址;没有它说明装的是旧版 App,直接报错,不回退 `/mcp`;
|
|
5
|
+
2. 请求是朴素的 `{tool, args}`,响应就是工具载荷本身,图片在同级 `image` 字段;
|
|
6
|
+
3. 鉴权通过、参数能解析之后一律 200,工具失败看载荷里的 `ok:false`。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
import socket
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Dict, Iterator, List, Mapping, Optional, Union
|
|
19
|
+
|
|
20
|
+
from .errors import InstallError, ToolError, TransportError
|
|
21
|
+
from .install import APP_VERSION
|
|
22
|
+
from .paths import mcp_file
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
'DEFAULT_TIMEOUT',
|
|
26
|
+
'Endpoint',
|
|
27
|
+
'ImagePart',
|
|
28
|
+
'CallResult',
|
|
29
|
+
'EventRecord',
|
|
30
|
+
'read_endpoint',
|
|
31
|
+
'Transport',
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
DEFAULT_TIMEOUT = 120.0
|
|
35
|
+
MAX_WAIT_MS = 25000
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Endpoint:
|
|
40
|
+
api: str
|
|
41
|
+
token: str
|
|
42
|
+
url: str = ''
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class ImagePart:
|
|
47
|
+
"""截图类工具才有:App 把图片放在同级 `image` 字段里。"""
|
|
48
|
+
|
|
49
|
+
mime_type: str
|
|
50
|
+
data: bytes
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class CallResult:
|
|
55
|
+
data: Dict[str, Any] = field(default_factory=dict)
|
|
56
|
+
image: Optional[ImagePart] = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class EventRecord:
|
|
61
|
+
seq: int
|
|
62
|
+
type: str
|
|
63
|
+
at: int
|
|
64
|
+
payload: Dict[str, Any] = field(default_factory=dict)
|
|
65
|
+
env: Optional[str] = None
|
|
66
|
+
tab_id: Optional[str] = None
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def of(cls, raw: Mapping[str, Any]) -> 'EventRecord':
|
|
70
|
+
return cls(
|
|
71
|
+
seq=int(raw.get('seq') or 0),
|
|
72
|
+
type=str(raw.get('type') or ''),
|
|
73
|
+
at=int(raw.get('at') or 0),
|
|
74
|
+
payload=dict(raw.get('payload') or {}),
|
|
75
|
+
env=raw.get('env'),
|
|
76
|
+
tab_id=raw.get('tabId'),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
EndpointLike = Union[Endpoint, Mapping[str, Any]]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _endpoint_of(value: EndpointLike) -> Endpoint:
|
|
84
|
+
if isinstance(value, Endpoint):
|
|
85
|
+
if not value.api:
|
|
86
|
+
raise InstallError(_missing_api())
|
|
87
|
+
return value
|
|
88
|
+
if isinstance(value, Mapping):
|
|
89
|
+
token = value.get('token')
|
|
90
|
+
api = value.get('api')
|
|
91
|
+
if token and not api:
|
|
92
|
+
raise InstallError(_missing_api())
|
|
93
|
+
if api and token:
|
|
94
|
+
return Endpoint(api=str(api).rstrip('/'), token=str(token), url=str(value.get('url') or ''))
|
|
95
|
+
raise TransportError('endpoint 需要 api 和 token,例如 {"api": "http://127.0.0.1:39221/api", "token": ...}')
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _missing_api() -> str:
|
|
99
|
+
return (
|
|
100
|
+
f'本机装的 BrowserPilot 太旧,没有 /api(对应 SDK v{APP_VERSION})。'
|
|
101
|
+
'请升级,或用 BROWSERPILOT_EXE 指定新版本。'
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def read_endpoint(file=None) -> Endpoint:
|
|
106
|
+
"""读取 App 写下的端点文件。没有 `api` 字段就是旧版,直接报错。"""
|
|
107
|
+
path = Path(file) if file is not None else Path(mcp_file())
|
|
108
|
+
if not path.is_file():
|
|
109
|
+
raise TransportError(
|
|
110
|
+
f'没找到 {path}。要么 BrowserPilot 没启动过,要么 MCP 在设置里被关掉了。'
|
|
111
|
+
)
|
|
112
|
+
try:
|
|
113
|
+
saved = json.loads(path.read_text(encoding='utf-8'))
|
|
114
|
+
except (OSError, ValueError) as error:
|
|
115
|
+
raise TransportError(f'{path} 不是合法的 JSON') from error
|
|
116
|
+
if not isinstance(saved, Mapping):
|
|
117
|
+
raise TransportError(f'{path} 里缺 token')
|
|
118
|
+
return _endpoint_of(saved)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Transport:
|
|
122
|
+
"""一个程序面端点的 HTTP 通道。"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, endpoint: EndpointLike, timeout: float = DEFAULT_TIMEOUT):
|
|
125
|
+
self.endpoint = _endpoint_of(endpoint)
|
|
126
|
+
self.timeout = timeout
|
|
127
|
+
self._closed = False
|
|
128
|
+
|
|
129
|
+
# ---------- 探活 / 目录 ----------
|
|
130
|
+
|
|
131
|
+
def ping(self, timeout: float = 2.0) -> bool:
|
|
132
|
+
"""App 没起来、端口被占、token 不对都算不通。"""
|
|
133
|
+
try:
|
|
134
|
+
self._request('GET', '/tools', timeout)
|
|
135
|
+
return True
|
|
136
|
+
except Exception: # noqa: BLE001 - 探活把一切异常都当「不通」
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
def tools(self) -> List[Dict[str, Any]]:
|
|
140
|
+
"""全量工具目录(不受 toolMode 影响)。"""
|
|
141
|
+
try:
|
|
142
|
+
payload = self._request('GET', '/tools', 10)
|
|
143
|
+
except TransportError:
|
|
144
|
+
return []
|
|
145
|
+
tools = payload.get('tools') if isinstance(payload, Mapping) else None
|
|
146
|
+
return list(tools or [])
|
|
147
|
+
|
|
148
|
+
# ---------- 调用 ----------
|
|
149
|
+
|
|
150
|
+
def call(
|
|
151
|
+
self,
|
|
152
|
+
name: str,
|
|
153
|
+
args: Optional[Mapping[str, Any]] = None,
|
|
154
|
+
timeout: Optional[float] = None,
|
|
155
|
+
) -> CallResult:
|
|
156
|
+
payload = self._request(
|
|
157
|
+
'POST',
|
|
158
|
+
'/call',
|
|
159
|
+
self.timeout if timeout is None else timeout,
|
|
160
|
+
{'tool': name, 'args': dict(args or {})},
|
|
161
|
+
)
|
|
162
|
+
if not isinstance(payload, Mapping):
|
|
163
|
+
raise TransportError(f'{name} 返回的不是 JSON 对象')
|
|
164
|
+
data = dict(payload)
|
|
165
|
+
image = None
|
|
166
|
+
raw_image = data.pop('image', None)
|
|
167
|
+
if isinstance(raw_image, Mapping) and raw_image.get('data'):
|
|
168
|
+
image = ImagePart(
|
|
169
|
+
mime_type=str(raw_image.get('mimeType') or 'image/png'),
|
|
170
|
+
data=base64.b64decode(str(raw_image['data'])),
|
|
171
|
+
)
|
|
172
|
+
# 工具失败是 200 + ok:false,这是唯一判据
|
|
173
|
+
if data.get('ok') is False:
|
|
174
|
+
raise ToolError(name, data)
|
|
175
|
+
return CallResult(data=data, image=image)
|
|
176
|
+
|
|
177
|
+
# ---------- 事件 ----------
|
|
178
|
+
|
|
179
|
+
def events(
|
|
180
|
+
self,
|
|
181
|
+
since: Optional[int] = None,
|
|
182
|
+
types: Optional[List[str]] = None,
|
|
183
|
+
env: Optional[str] = None,
|
|
184
|
+
tab_id: Optional[str] = None,
|
|
185
|
+
wait_ms: int = MAX_WAIT_MS,
|
|
186
|
+
limit: Optional[int] = None,
|
|
187
|
+
) -> Dict[str, Any]:
|
|
188
|
+
"""长轮询取一批事件。返回原始结果(events / seq / reset / timeout)。"""
|
|
189
|
+
body: Dict[str, Any] = {'wait': max(0, min(MAX_WAIT_MS, int(wait_ms)))}
|
|
190
|
+
if since is not None:
|
|
191
|
+
body['since'] = since
|
|
192
|
+
if types:
|
|
193
|
+
body['types'] = list(types)
|
|
194
|
+
if env:
|
|
195
|
+
body['env'] = env
|
|
196
|
+
if tab_id:
|
|
197
|
+
body['tabId'] = tab_id
|
|
198
|
+
if limit is not None:
|
|
199
|
+
body['limit'] = limit
|
|
200
|
+
# 客户端要比服务端挂得久一点,否则先超时的会是客户端
|
|
201
|
+
payload = self._request('POST', '/events', body['wait'] / 1000 + 10, body)
|
|
202
|
+
return dict(payload or {})
|
|
203
|
+
|
|
204
|
+
def event_stream(
|
|
205
|
+
self,
|
|
206
|
+
types: Optional[List[str]] = None,
|
|
207
|
+
env: Optional[str] = None,
|
|
208
|
+
tab_id: Optional[str] = None,
|
|
209
|
+
since: Optional[int] = None,
|
|
210
|
+
) -> Iterator[EventRecord]:
|
|
211
|
+
"""无限迭代事件。用 `break` 退出。"""
|
|
212
|
+
while True:
|
|
213
|
+
result = self.events(since=since, types=types, env=env, tab_id=tab_id)
|
|
214
|
+
since = result.get('seq', since)
|
|
215
|
+
for raw in result.get('events') or []:
|
|
216
|
+
yield EventRecord.of(raw)
|
|
217
|
+
|
|
218
|
+
def close(self) -> None:
|
|
219
|
+
self._closed = True
|
|
220
|
+
|
|
221
|
+
# ---------- 内部 ----------
|
|
222
|
+
|
|
223
|
+
def _request(self, method: str, path: str, timeout: float, body: Optional[Mapping[str, Any]] = None):
|
|
224
|
+
if self._closed:
|
|
225
|
+
raise TransportError('连接已经关了')
|
|
226
|
+
url = f'{self.endpoint.api}{path}'
|
|
227
|
+
data = None if body is None else json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
228
|
+
headers = {'Authorization': f'Bearer {self.endpoint.token}'}
|
|
229
|
+
if data is not None:
|
|
230
|
+
headers['Content-Type'] = 'application/json'
|
|
231
|
+
request = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
232
|
+
try:
|
|
233
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
234
|
+
text = response.read().decode('utf-8', 'replace')
|
|
235
|
+
except urllib.error.HTTPError as error:
|
|
236
|
+
if error.code == 401:
|
|
237
|
+
raise TransportError('token 不对,重新读一遍 mcp.json') from error
|
|
238
|
+
if error.code == 403:
|
|
239
|
+
raise TransportError('被 Origin 校验挡下了') from error
|
|
240
|
+
detail = error.read().decode('utf-8', 'replace')[:200]
|
|
241
|
+
raise TransportError(f'HTTP {error.code} {detail}') from error
|
|
242
|
+
except (socket.timeout, TimeoutError) as error:
|
|
243
|
+
raise TransportError(f'等了 {int(timeout * 1000)}ms 没回应') from error
|
|
244
|
+
except urllib.error.URLError as error:
|
|
245
|
+
if isinstance(error.reason, (socket.timeout, TimeoutError)):
|
|
246
|
+
raise TransportError(f'等了 {int(timeout * 1000)}ms 没回应') from error
|
|
247
|
+
raise TransportError(f'连不上 {self.endpoint.api}') from error
|
|
248
|
+
except OSError as error:
|
|
249
|
+
raise TransportError(f'连不上 {self.endpoint.api}') from error
|
|
250
|
+
try:
|
|
251
|
+
return json.loads(text) if text else {}
|
|
252
|
+
except ValueError as error:
|
|
253
|
+
raise TransportError(f'{path} 返回的不是 JSON:{text[:200]}') from error
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: browserpilot-sdk
|
|
3
|
+
Version: 0.19.0
|
|
4
|
+
Summary: Drive the BrowserPilot desktop browser from Python, Playwright style
|
|
5
|
+
Author-email: xy200303 <3483421977@qq.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/xy200303/browserpilot
|
|
8
|
+
Project-URL: Repository, https://github.com/xy200303/browserpilot
|
|
9
|
+
Project-URL: Documentation, https://github.com/xy200303/browserpilot/blob/main/sdk/README.md
|
|
10
|
+
Project-URL: Issues, https://github.com/xy200303/browserpilot/issues
|
|
11
|
+
Keywords: browser,automation,mcp,playwright,browserpilot
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Classifier: Operating System :: MacOS
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# BrowserPilot Python SDK
|
|
24
|
+
|
|
25
|
+
用 Playwright 的样子驱动本机的 BrowserPilot 桌面浏览器。零运行时依赖,只用标准库,Python 3.9+。
|
|
26
|
+
|
|
27
|
+
SDK **不自带浏览器引擎**,它驱动的是你机器上那扇 BrowserPilot 窗口:登录态、书签、密码都还在,
|
|
28
|
+
脚本和 Agent 操作的是同一套 cookie。发现、下载、传输的行为和 Node 版逐条对齐。
|
|
29
|
+
|
|
30
|
+
## 安装
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install browserpilot-sdk
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
源码目录里开发:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install -e sdk/python
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 快速开始
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from browserpilot import launch
|
|
46
|
+
|
|
47
|
+
# 也支持不加 with
|
|
48
|
+
with launch(headless=True) as bp:
|
|
49
|
+
page = bp.new_page()
|
|
50
|
+
page.goto("https://example.com")
|
|
51
|
+
page.get_by_role("button", name="登录").click()
|
|
52
|
+
page.get_by_label("账号").fill("小明")
|
|
53
|
+
page.locator("#submit").click()
|
|
54
|
+
page.get_by_text("完成").wait_for()
|
|
55
|
+
page.wait_for_text("完成", timeout=10)
|
|
56
|
+
page.screenshot(path="a.png") # 返回 bytes
|
|
57
|
+
print(page.title(), page.url())
|
|
58
|
+
bp.close()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## 找 BrowserPilot 的顺序
|
|
62
|
+
|
|
63
|
+
**先找已经装好的,再考虑下载。** 用户机器上那份桌面版就是首选,因为登录态都在它那儿。
|
|
64
|
+
|
|
65
|
+
| 顺序 | 条件 | 说明 |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| 1 | `BROWSERPILOT_EXE` 环境变量 | 指向可执行文件,优先级最高,CI 里常用 |
|
|
68
|
+
| 2 | 已经在跑的实例 | 端点文件存在且 `GET {api}/tools` 能通,直接连上,不启动任何进程 |
|
|
69
|
+
| 3 | 桌面版安装位置 | Windows `%LOCALAPPDATA%\Programs\BrowserPilot\`、macOS `/Applications/BrowserPilot.app`、Linux `/opt/BrowserPilot/` |
|
|
70
|
+
| 4 | SDK 自己的缓存 | `~/.browserpilot/sdk/<version>/` |
|
|
71
|
+
| 5 | 下载 | 只有在前面都失败时才发生 |
|
|
72
|
+
|
|
73
|
+
下载只在需要时进行:从 GitHub Release 取 `v<version>` 的资产,边下边算 SHA-256 和 API 的
|
|
74
|
+
`digest` 比对,临时文件用 `.part` 后缀,解压到 `~/.browserpilot/sdk/<version>/`。
|
|
75
|
+
平台矩阵只认实际发布过的三种:Windows x64(zip)、macOS arm64(zip)、Linux x64(AppImage),
|
|
76
|
+
其余组合直接报 `InstallError`,不会下到一半才崩。
|
|
77
|
+
|
|
78
|
+
## 环境变量
|
|
79
|
+
|
|
80
|
+
| 变量 | 作用 |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `BROWSERPILOT_EXE` | 指定 App 可执行文件,跳过发现流程 |
|
|
83
|
+
| `BROWSERPILOT_HOME` | 改 `~/.browserpilot` 的位置(缓存和下载目录) |
|
|
84
|
+
| `BROWSERPILOT_OFFLINE=1` | 只找不下载,找不到直接报错 |
|
|
85
|
+
| `BROWSERPILOT_STRICT_VERSION=1` | 已装版本和 SDK 不一致时报错,而不是警告 |
|
|
86
|
+
| `BROWSERPILOT_DEBUG=1` | 把发现/启动的过程打到 stderr |
|
|
87
|
+
| `GITHUB_TOKEN` | 下载时带上,避免 GitHub API 限流 |
|
|
88
|
+
|
|
89
|
+
## API
|
|
90
|
+
|
|
91
|
+
### `launch(...)`
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
launch(env=None, headless=None, timeout=60, exe=None, version=None,
|
|
95
|
+
endpoint=None, offline=False, strict_version=False,
|
|
96
|
+
on_download=None, log=None) -> BrowserPilot
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
- `env`:用哪套环境,默认 `env-default`
|
|
100
|
+
- `headless`:`True` 时把窗口切成无头(窗口仍然存在,只是不显示);`False` 不会主动开窗,免得把用户正在用的窗口拉到前台
|
|
101
|
+
- `timeout`:等 App 起来的秒数,首次下载不占这个时间
|
|
102
|
+
- `endpoint`:直接连一个已知端点(`{"url": ..., "token": ...}` 或 `Endpoint`),跳过发现
|
|
103
|
+
- `on_download(progress)`:下载进度回调,`progress` 是 `{"asset", "received", "total"}`
|
|
104
|
+
|
|
105
|
+
已经在跑的实例只会被连上,**不会拉起第二个**(App 有单实例锁,第二个会自己退出)。
|
|
106
|
+
|
|
107
|
+
### `connect(endpoint=None, timeout=120, log=None)`
|
|
108
|
+
|
|
109
|
+
只连已经在跑的实例,没有就抛 `TransportError`。适合「必须用用户当前那扇窗口」的场景。
|
|
110
|
+
|
|
111
|
+
### `BrowserPilot`
|
|
112
|
+
|
|
113
|
+
| 成员 | 说明 |
|
|
114
|
+
| --- | --- |
|
|
115
|
+
| `new_page(url=None, env=None)` | `tab_open`,返回 `Page` |
|
|
116
|
+
| `pages()` | 所有标签 |
|
|
117
|
+
| `environments()` | 所有环境 |
|
|
118
|
+
| `environment(id)` | 取一套环境,可 `open()` / `close()` / `new_page()` / `pages()` |
|
|
119
|
+
| `call(tool, args=None)` | 原始工具调用,参数原样透传 |
|
|
120
|
+
| `locator(selector)` | 当前第一页上的定位器 |
|
|
121
|
+
| `close()` | 只关自己开的环境;连的是别人的实例时什么都不做 |
|
|
122
|
+
| `env_id` / `sdk_version` / `app_version` | `app_version` 只有 SDK 自己装的那份才知道 |
|
|
123
|
+
|
|
124
|
+
支持 `with`,退出时调用 `close()`。
|
|
125
|
+
|
|
126
|
+
### `Page`
|
|
127
|
+
|
|
128
|
+
| 成员 | 说明 |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `goto` `reload` `back` `forward` | 导航,`goto` 内部已经等到 load 完成 |
|
|
131
|
+
| `wait_for_load(timeout=15)` | 等 `did-stop-loading` |
|
|
132
|
+
| `url()` `title()` | 从 `tab_list` 里读 |
|
|
133
|
+
| `get_by_role` `get_by_text` `get_by_label` `get_by_placeholder` `get_by_test_id` `locator` `xpath` | 定位器工厂 |
|
|
134
|
+
| `click` `fill` `type` `press` `hover` `select` `scroll` `scroll_to` | 动作 |
|
|
135
|
+
| `wait_for` `wait_for_text` `expect_text` | 等待 |
|
|
136
|
+
| `count` `is_visible` `text_content` `content` `snapshot` `evaluate` `console_logs` | 读取 |
|
|
137
|
+
| `screenshot(path=None, ...)` | 返回 `bytes`,给了 `path` 就顺手写一份 |
|
|
138
|
+
| `bring_to_front` `close` | 标签生命周期 |
|
|
139
|
+
| `call(tool, args=None)` | 原始调用,自动带 `tabId` |
|
|
140
|
+
| `id` / `env` | 标签 id 和所属环境 |
|
|
141
|
+
|
|
142
|
+
支持 `with page:`,退出时关掉这个标签。
|
|
143
|
+
|
|
144
|
+
### `Locator`
|
|
145
|
+
|
|
146
|
+
`click` `dblclick` `fill` `type` `hover` `select_option` `scroll_into_view` `wait_for`
|
|
147
|
+
`count` `is_visible` `text_content` `screenshot`,以及收窄用的 `nth` `first` `within` `pierce`。
|
|
148
|
+
|
|
149
|
+
`Page` 和 `Locator` 都接受三种定位目标:CSS 选择器字符串、`Locator`、
|
|
150
|
+
或者字典(`{"role": "button", "name": "登录"}`,键名同时认 `testId` 和 `test_id`)。
|
|
151
|
+
|
|
152
|
+
## 事件
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
before = bp.call('env_list') # 任何工具结果里都有 seq
|
|
156
|
+
page.goto('https://example.com')
|
|
157
|
+
|
|
158
|
+
for event in bp.events(since=before['seq']):
|
|
159
|
+
print(event.type, event.payload)
|
|
160
|
+
break # 生成器不会自己结束
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
一步拿一批、不等推送:`bp.transport.events(since=..., wait_ms=25000)`。
|
|
164
|
+
位置失效(App 重启或超出缓冲)时返回里带 `reset`,客户端应该用工具重建状态。
|
|
165
|
+
|
|
166
|
+
## 和 Playwright 不一样的地方
|
|
167
|
+
|
|
168
|
+
| 差异 | 原因 |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `fill()` 要发三次调用(聚焦 → 全选 → 粘贴) | `page_type` 底层是 `Input.insertText`,只在光标处插入、不清空;selector/xpath 例外,一次 `via="inject"` 就够 |
|
|
171
|
+
| 不能开多个浏览器,隔离单位是「环境」 | App 是单实例应用 |
|
|
172
|
+
| 事件是长轮询批量拿,不是回调 | 没有推送通道;用 `bp.events()` 或 `bp.transport.events()` 自己筛 |
|
|
173
|
+
| `goto()` 不知道「网络空闲」 | 只有 `did-stop-loading`,需要时补 `wait_for_load()` 或 `locator.wait_for()` |
|
|
174
|
+
| `screenshot()` 默认 `grid=False` | App 默认会画坐标网格(给人点位置用),SDK 里那是噪点 |
|
|
175
|
+
| `evaluate()` 只收 JS 源码字符串 | Python 函数没法序列化进页面;Node 版会把函数 `toString()` |
|
|
176
|
+
| `click()` 按 text → role+name → selector/xpath → testId/alt 映射 | 工具本身就按这个优先级找元素;`label` / `placeholder` 定位器点不了,得改写成 selector |
|
|
177
|
+
|
|
178
|
+
其他限制:Linux 无头仍然需要 `Xvfb`(Electron 起窗口要 display);二进制没有代码签名,
|
|
179
|
+
macOS 首次运行可能需要 `xattr -cr`。
|
|
180
|
+
|
|
181
|
+
## 测试
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
cd sdk/python
|
|
185
|
+
python -m unittest discover -s tests -v
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
测试不联网、不启动真实 App:`tests/test_sdk.py` 里起一个假的 `/api` 端点(Bearer 鉴权、
|
|
189
|
+
`{tool, args}` 进、图片放同级的 `image`),断言 SDK 到底发出了哪些工具调用。
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
browserpilot/__init__.py,sha256=u2U56WwNKKTpWyd2TaYgLJ0DvrjneXsEqyX9q4qaS0M,1671
|
|
2
|
+
browserpilot/client.py,sha256=m59BchfOxefc9Nn3PNADXYygAZK3uXV3IujWIJj9hfA,11089
|
|
3
|
+
browserpilot/errors.py,sha256=WsvlKZ4i4gF7vl09VMps7KaEcaC4MbcCLLrjJ0U0jLM,1359
|
|
4
|
+
browserpilot/install.py,sha256=ubkWsD4uBYcKnmi3tS6gJvhv3Lsp3D4h9B24wCbrAOI,9402
|
|
5
|
+
browserpilot/locator.py,sha256=KLM63awF2SMh9DN-ZePlzcD_brJ3KBbwSIFLOgMC1yI,8817
|
|
6
|
+
browserpilot/page.py,sha256=zzOmBsnCqa3FQ2NxPB3CZeaFZxLZfUEoUSncEqQOMeo,15717
|
|
7
|
+
browserpilot/paths.py,sha256=Drq3ypYm_R6yhADmBmQfHsGkdmBxwlMFqIcok_jeXQk,4313
|
|
8
|
+
browserpilot/transport.py,sha256=5MFPdKrclQL1MkIe5Y0BrZNc5myHX4RGn8hKbBpP594,8937
|
|
9
|
+
browserpilot_sdk-0.19.0.dist-info/METADATA,sha256=pT471ewVq9hofj3-lEsiy8Admp2zyIM5FHmraJMVNKM,8517
|
|
10
|
+
browserpilot_sdk-0.19.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
browserpilot_sdk-0.19.0.dist-info/top_level.txt,sha256=a4Rv_k4qFNyR_PgtxsGqrUqA17uLsqMJtNq2ceZOigQ,13
|
|
12
|
+
browserpilot_sdk-0.19.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
browserpilot
|