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.
@@ -0,0 +1,270 @@
1
+ """定位器:只记录「用户想怎么找」,能不能这样找由各个动作决定。
2
+
3
+ BrowserPilot 的工具不是每个都支持全部定位方式:点击支持 text / role+name /
4
+ xpath / selector,输入只支持 label / placeholder / xpath / selector。
5
+ 所以这里保留定位意图,由各个动作自己翻译成工具参数。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, replace
12
+ from typing import Any, Dict, NamedTuple, Optional
13
+
14
+ from .errors import NotFoundError
15
+
16
+ __all__ = [
17
+ 'LocatorSpec',
18
+ 'Locator',
19
+ 'is_locator_spec',
20
+ 'coerce_spec',
21
+ 'describe',
22
+ 'action_args',
23
+ 'type_plan',
24
+ 'wait_args',
25
+ 'TypePlan',
26
+ ]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class LocatorSpec:
31
+ role: Optional[str] = None
32
+ name: Optional[str] = None
33
+ # 'exact' 或 'contains',None 表示让工具自己决定。
34
+ name_match: Optional[str] = None
35
+ text: Optional[str] = None
36
+ text_match: Optional[str] = None
37
+ # 关联的 label 或 placeholder。
38
+ label: Optional[str] = None
39
+ placeholder: Optional[str] = None
40
+ test_id: Optional[str] = None
41
+ alt: Optional[str] = None
42
+ selector: Optional[str] = None
43
+ xpath: Optional[str] = None
44
+ # 缩小范围的 CSS 容器,支持 :has-text()。
45
+ within: Optional[str] = None
46
+ # 多个匹配时取第几个,从 0 开始。
47
+ index: Optional[int] = None
48
+ # 搜索 shadow DOM 和同源 iframe。
49
+ pierce: bool = False
50
+
51
+
52
+ # 字典写法和 Node 版的 camelCase 都认,用户不必背工具参数名。
53
+ _ALIASES = {
54
+ 'role': 'role',
55
+ 'name': 'name',
56
+ 'nameMatch': 'name_match',
57
+ 'name_match': 'name_match',
58
+ 'text': 'text',
59
+ 'textMatch': 'text_match',
60
+ 'text_match': 'text_match',
61
+ 'label': 'label',
62
+ 'placeholder': 'placeholder',
63
+ 'testId': 'test_id',
64
+ 'test_id': 'test_id',
65
+ 'alt': 'alt',
66
+ 'selector': 'selector',
67
+ 'xpath': 'xpath',
68
+ 'within': 'within',
69
+ 'index': 'index',
70
+ 'pierce': 'pierce',
71
+ }
72
+
73
+
74
+ def is_locator_spec(value: Any) -> bool:
75
+ return isinstance(value, Mapping) and any(key in _ALIASES for key in value)
76
+
77
+
78
+ def coerce_spec(value: Any) -> LocatorSpec:
79
+ """把字符串 / 字典 / LocatorSpec 统一成 LocatorSpec。"""
80
+ if isinstance(value, LocatorSpec):
81
+ return value
82
+ if isinstance(value, str):
83
+ return LocatorSpec(selector=value)
84
+ if isinstance(value, Mapping):
85
+ fields: Dict[str, Any] = {}
86
+ for key, item in value.items():
87
+ field = _ALIASES.get(key)
88
+ if field is None:
89
+ raise TypeError(f'定位描述里没有 {key} 这个字段')
90
+ fields[field] = item
91
+ if not fields:
92
+ raise TypeError('定位描述是空的')
93
+ return LocatorSpec(**fields)
94
+ raise TypeError('定位目标必须是 CSS 选择器字符串、Locator 或定位描述字典')
95
+
96
+
97
+ def describe(spec: LocatorSpec) -> str:
98
+ """给人看的描述,用在报错里。"""
99
+ if spec.role:
100
+ return f'role={spec.role}' + (f' name={spec.name}' if spec.name else '')
101
+ if spec.text:
102
+ return f'text={spec.text}'
103
+ if spec.label:
104
+ return f'label={spec.label}'
105
+ if spec.placeholder:
106
+ return f'placeholder={spec.placeholder}'
107
+ if spec.test_id:
108
+ return f'testId={spec.test_id}'
109
+ if spec.alt:
110
+ return f'alt={spec.alt}'
111
+ if spec.xpath:
112
+ return f'xpath={spec.xpath}'
113
+ if spec.selector:
114
+ return f'selector={spec.selector}'
115
+ return '空定位器'
116
+
117
+
118
+ def action_args(spec: LocatorSpec) -> Dict[str, Any]:
119
+ """page_click / page_hover 的定位字段。顺序按工具建议:text 优先,然后 role+name。"""
120
+ args: Dict[str, Any] = {}
121
+ if spec.text:
122
+ args['text'] = spec.text
123
+ if spec.text_match:
124
+ args['textMatch'] = spec.text_match
125
+ elif spec.role:
126
+ args['role'] = spec.role
127
+ if spec.name:
128
+ args['name'] = spec.name
129
+ if spec.name_match:
130
+ args['nameMatch'] = spec.name_match
131
+ elif spec.selector:
132
+ args['selector'] = spec.selector
133
+ if spec.pierce:
134
+ args['pierce'] = True
135
+ elif spec.xpath:
136
+ args['xpath'] = spec.xpath
137
+ if spec.pierce:
138
+ args['pierce'] = True
139
+ elif spec.test_id:
140
+ args['testId'] = spec.test_id
141
+ elif spec.alt:
142
+ args['alt'] = spec.alt
143
+ if spec.within:
144
+ args['within'] = spec.within
145
+ if spec.index is not None:
146
+ args['index'] = spec.index
147
+ return args
148
+
149
+
150
+ class TypePlan(NamedTuple):
151
+ # 'inject':一次调用直接覆盖;'focus':先聚焦再插入,要三步。
152
+ mode: str
153
+ args: Dict[str, Any]
154
+
155
+
156
+ def type_plan(spec: LocatorSpec) -> TypePlan:
157
+ """page_type 只认 label / placeholder / xpath / selector。
158
+
159
+ role+name 的输入框通常就是文本框,它的可访问名一般也是 label,退一步用它当 label。
160
+ """
161
+ if spec.selector:
162
+ args: Dict[str, Any] = {'selector': spec.selector}
163
+ if spec.pierce:
164
+ args['pierce'] = True
165
+ return TypePlan('inject', args)
166
+ if spec.xpath:
167
+ args = {'xpath': spec.xpath}
168
+ if spec.pierce:
169
+ args['pierce'] = True
170
+ return TypePlan('inject', args)
171
+ if spec.label:
172
+ return TypePlan('focus', {'label': spec.label})
173
+ if spec.placeholder:
174
+ return TypePlan('focus', {'placeholder': spec.placeholder})
175
+ if spec.role in ('textbox', 'searchbox', 'combobox') and spec.name:
176
+ return TypePlan('focus', {'label': spec.name})
177
+ raise NotFoundError(
178
+ f'无法输入 {describe(spec)}:page_type 只支持 selector、xpath、label、placeholder,'
179
+ '以及 role=textbox/searchbox/combobox 且带 name 的定位器。'
180
+ )
181
+
182
+
183
+ def wait_args(spec: LocatorSpec, state: str, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]:
184
+ """page_wait 只认 xpath / selector。返回 None 表示这个定位器得靠轮询。"""
185
+ args: Dict[str, Any] = {'state': state}
186
+ if timeout is not None:
187
+ args['timeout'] = timeout
188
+ if spec.selector:
189
+ args['selector'] = spec.selector
190
+ if spec.pierce:
191
+ args['pierce'] = True
192
+ return args
193
+ if spec.xpath:
194
+ args['xpath'] = spec.xpath
195
+ if spec.pierce:
196
+ args['pierce'] = True
197
+ return args
198
+ return None
199
+
200
+
201
+ class Locator:
202
+ """链式定位器。每个动作都落在当前页面上,页面上唯一匹配才算成功(工具本身就这么要求)。"""
203
+
204
+ def __init__(self, page, spec):
205
+ self.page = page
206
+ self.spec = coerce_spec(spec)
207
+
208
+ # ---------- 收窄 ----------
209
+
210
+ def nth(self, index: int) -> 'Locator':
211
+ """多个匹配时取第 index 个,从 0 开始。"""
212
+ return Locator(self.page, replace(self.spec, index=index))
213
+
214
+ def first(self) -> 'Locator':
215
+ return self.nth(0)
216
+
217
+ def within(self, selector: str) -> 'Locator':
218
+ """在某个容器里找。"""
219
+ return Locator(self.page, replace(self.spec, within=selector))
220
+
221
+ def pierce(self) -> 'Locator':
222
+ """进 shadow DOM 和同源 iframe 里找。"""
223
+ return Locator(self.page, replace(self.spec, pierce=True))
224
+
225
+ # ---------- 动作 ----------
226
+
227
+ def click(self, button=None, count=None, timeout=None, via=None) -> None:
228
+ return self.page.click(self.spec, button=button, count=count, timeout=timeout, via=via)
229
+
230
+ def dblclick(self) -> None:
231
+ return self.page.click(self.spec, count=2)
232
+
233
+ def fill(self, value: str) -> None:
234
+ """Playwright 语义:覆盖已有内容。selector/xpath 一次调用,其余要三步。"""
235
+ return self.page.fill(self.spec, value)
236
+
237
+ def type(self, value: str) -> None:
238
+ """在光标处追加,不清空。"""
239
+ return self.page.type(self.spec, value)
240
+
241
+ def hover(self) -> None:
242
+ return self.page.hover(self.spec)
243
+
244
+ def select_option(self, option: str) -> None:
245
+ return self.page.select(self.spec, option)
246
+
247
+ def scroll_into_view(self) -> None:
248
+ return self.page.scroll_to(self.spec)
249
+
250
+ # ---------- 等待与读取 ----------
251
+
252
+ def wait_for(self, state: str = 'appear', timeout: float = 10, poll_ms: Optional[int] = None) -> None:
253
+ return self.page.wait_for(self.spec, state=state, timeout=timeout, poll_ms=poll_ms)
254
+
255
+ def count(self) -> int:
256
+ return self.page.count(self.spec)
257
+
258
+ def is_visible(self) -> bool:
259
+ return self.page.is_visible(self.spec)
260
+
261
+ def text_content(self) -> str:
262
+ return self.page.text_content(self.spec)
263
+
264
+ def screenshot(self, path: Optional[str] = None) -> bytes:
265
+ return self.page.screenshot(path=path, target=self.spec)
266
+
267
+ def __str__(self) -> str:
268
+ return f'Locator({describe(self.spec)})'
269
+
270
+ __repr__ = __str__
browserpilot/page.py ADDED
@@ -0,0 +1,406 @@
1
+ """Playwright 风格的页面封装。
2
+
3
+ 每个动作都直接落到 MCP 工具上,参数映射照 Node 版逐条对齐:
4
+ `page_click` 按 text → role+name → selector/xpath → testId/alt 排优先级,
5
+ `fill` 对 selector/xpath 一次 inject,其余靠「聚焦 → 全选 → 粘贴」三步。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ import time
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional, Union
15
+
16
+ from .errors import BrowserPilotError, NotFoundError, ToolError
17
+ from .locator import (
18
+ Locator,
19
+ LocatorSpec,
20
+ action_args,
21
+ coerce_spec,
22
+ describe,
23
+ type_plan,
24
+ wait_args,
25
+ )
26
+ from .transport import Transport
27
+
28
+ __all__ = ['Page', 'PageTarget', 'DEFAULT_MODIFIER']
29
+
30
+ # 定位目标:CSS 选择器、Locator、或者直接给一份定位描述。
31
+ PageTarget = Union[str, Locator, LocatorSpec, Mapping[str, Any]]
32
+
33
+ # page_type 的底层是 Input.insertText,只在光标处插入,覆盖语义得先全选。
34
+ DEFAULT_MODIFIER = 'Meta+A' if sys.platform == 'darwin' else 'Control+A'
35
+
36
+
37
+ def _locate_fields(spec: LocatorSpec) -> Optional[Dict[str, Any]]:
38
+ if spec.selector:
39
+ fields: Dict[str, Any] = {'selector': spec.selector}
40
+ if spec.pierce:
41
+ fields['pierce'] = True
42
+ return fields
43
+ if spec.xpath:
44
+ fields = {'xpath': spec.xpath}
45
+ if spec.pierce:
46
+ fields['pierce'] = True
47
+ return fields
48
+ return None
49
+
50
+
51
+ def _as_int(value: Any, default: int = 0) -> int:
52
+ try:
53
+ return int(value)
54
+ except (TypeError, ValueError):
55
+ return default
56
+
57
+
58
+ class Page:
59
+ """一个标签页。构造时拿到的 transport 和 env 就定下来了。"""
60
+
61
+ def __init__(self, transport: Transport, id: str, env: str):
62
+ self._transport = transport
63
+ self.id = id
64
+ self.env = env
65
+
66
+ def __enter__(self) -> 'Page':
67
+ return self
68
+
69
+ def __exit__(self, exc_type, exc, traceback) -> bool:
70
+ # with 结束就关掉这个标签;后台的 App 不受影响。
71
+ self.close()
72
+ return False
73
+
74
+ def __str__(self) -> str:
75
+ return f'Page({self.id})'
76
+
77
+ def call(
78
+ self,
79
+ tool: str,
80
+ args: Optional[Mapping[str, Any]] = None,
81
+ timeout: Optional[float] = None,
82
+ ) -> Dict[str, Any]:
83
+ """原始工具调用,参数里自动带上 tabId。SDK 没封装的工具都从这里走。"""
84
+ return self._raw(tool, dict(args or {}), timeout=timeout).data
85
+
86
+ # ---------- 导航 ----------
87
+
88
+ def goto(self, url: str) -> Dict[str, Any]:
89
+ """打开地址。page_navigate 内部已经等到 load 完成,不用再补等待。"""
90
+ return self._raw('page_navigate', {'url': url}).data
91
+
92
+ def reload(self) -> Dict[str, Any]:
93
+ return self._raw('page_reload', {}).data
94
+
95
+ def back(self) -> Dict[str, Any]:
96
+ return self._raw('page_back', {}).data
97
+
98
+ def forward(self) -> Dict[str, Any]:
99
+ return self._raw('page_forward', {}).data
100
+
101
+ def wait_for_load(self, timeout: float = 15) -> Dict[str, Any]:
102
+ """等 did-stop-loading。跳转和点链接之后比 sleep 可靠。"""
103
+ return self._raw('page_wait_load', {'timeout': timeout}).data
104
+
105
+ def url(self) -> str:
106
+ return self._info()['url']
107
+
108
+ def title(self) -> str:
109
+ return self._info()['title']
110
+
111
+ # ---------- 定位 ----------
112
+
113
+ def get_by_role(self, role: str, name: Optional[str] = None, exact: Optional[bool] = None) -> Locator:
114
+ return Locator(
115
+ self,
116
+ LocatorSpec(
117
+ role=role,
118
+ name=name,
119
+ name_match=None if exact is None else ('exact' if exact else 'contains'),
120
+ ),
121
+ )
122
+
123
+ def get_by_text(self, text: str, exact: Optional[bool] = None) -> Locator:
124
+ return Locator(
125
+ self,
126
+ LocatorSpec(text=text, text_match=None if exact is None else ('exact' if exact else 'contains')),
127
+ )
128
+
129
+ def get_by_label(self, label: str) -> Locator:
130
+ return Locator(self, LocatorSpec(label=label))
131
+
132
+ def get_by_placeholder(self, placeholder: str) -> Locator:
133
+ return Locator(self, LocatorSpec(placeholder=placeholder))
134
+
135
+ def get_by_test_id(self, test_id: str) -> Locator:
136
+ return Locator(self, LocatorSpec(test_id=test_id))
137
+
138
+ def locator(self, selector: str) -> Locator:
139
+ return Locator(self, LocatorSpec(selector=selector))
140
+
141
+ def xpath(self, xpath: str) -> Locator:
142
+ return Locator(self, LocatorSpec(xpath=xpath))
143
+
144
+ # ---------- 动作 ----------
145
+
146
+ def click(
147
+ self,
148
+ target: PageTarget,
149
+ button: Optional[str] = None,
150
+ count: Optional[int] = None,
151
+ timeout: Optional[float] = None,
152
+ via: Optional[str] = None,
153
+ ) -> Dict[str, Any]:
154
+ args = action_args(self._spec_of(target))
155
+ if button:
156
+ args['button'] = button
157
+ if count:
158
+ args['count'] = count
159
+ if via:
160
+ args['via'] = via
161
+ return self._raw('page_click', args, timeout=timeout).data
162
+
163
+ def fill(self, target: PageTarget, value: str) -> Dict[str, Any]:
164
+ """覆盖式输入。
165
+
166
+ selector/xpath 一次 inject 搞定;label / placeholder / role 走
167
+ 「聚焦 → 全选 → 粘贴」三步,因为 page_type 只在光标处插入、不清空。
168
+ """
169
+ plan = type_plan(self._spec_of(target))
170
+ if plan.mode == 'inject':
171
+ return self._raw('page_type', {**plan.args, 'text': value, 'via': 'inject'}).data
172
+ self._raw('page_type', {**plan.args, 'text': ''})
173
+ self.press(DEFAULT_MODIFIER)
174
+ return self._raw('page_type', {**plan.args, 'text': value, 'entry': 'paste'}).data
175
+
176
+ def type(self, target: PageTarget, value: str) -> Dict[str, Any]:
177
+ """在光标处追加,不清空。"""
178
+ plan = type_plan(self._spec_of(target))
179
+ # inject 只给 fill 用,所以这里不带 via。
180
+ return self._raw('page_type', {**plan.args, 'text': value}).data
181
+
182
+ def press(self, shortcut: str, via: Optional[str] = None) -> Dict[str, Any]:
183
+ """快捷键进页面,例如 Control+Enter;不会触发窗口自己的新建/关闭标签。"""
184
+ args: Dict[str, Any] = {'shortcut': shortcut}
185
+ if via:
186
+ args['via'] = via
187
+ return self._raw('page_key', args).data
188
+
189
+ def hover(self, target: PageTarget) -> Dict[str, Any]:
190
+ return self._raw('page_hover', action_args(self._spec_of(target))).data
191
+
192
+ def select(self, target: PageTarget, option: str) -> Dict[str, Any]:
193
+ spec = self._spec_of(target)
194
+ fields = _locate_fields(spec)
195
+ if fields is None:
196
+ raise NotFoundError(f'selectOption 只支持 selector 或 xpath,收到 {describe(spec)}')
197
+ return self._raw('page_select', {**fields, 'option': option}).data
198
+
199
+ def scroll(
200
+ self,
201
+ direction: str = 'down',
202
+ target: Optional[PageTarget] = None,
203
+ until: Optional[PageTarget] = None,
204
+ ) -> Dict[str, Any]:
205
+ args: Dict[str, Any] = {'direction': direction}
206
+ if target is not None:
207
+ args.update(_locate_fields(self._spec_of(target)) or {})
208
+ if until is not None:
209
+ until_spec = self._spec_of(until)
210
+ if until_spec.selector:
211
+ args['untilSelector'] = until_spec.selector
212
+ if until_spec.xpath:
213
+ args['untilXpath'] = until_spec.xpath
214
+ return self._raw('page_scroll', args).data
215
+
216
+ def scroll_to(self, target: PageTarget) -> Dict[str, Any]:
217
+ """滚到目标能被点到为止。"""
218
+ spec = self._spec_of(target)
219
+ args: Dict[str, Any] = {'direction': 'down'}
220
+ if spec.selector:
221
+ args['untilSelector'] = spec.selector
222
+ elif spec.xpath:
223
+ args['untilXpath'] = spec.xpath
224
+ else:
225
+ raise NotFoundError(f'scrollTo 只支持 selector 或 xpath,收到 {describe(spec)}')
226
+ return self._raw('page_scroll', args).data
227
+
228
+ # ---------- 等待 ----------
229
+
230
+ def wait_for(
231
+ self,
232
+ target: PageTarget,
233
+ state: str = 'appear',
234
+ timeout: float = 10,
235
+ poll_ms: Optional[int] = None,
236
+ ) -> None:
237
+ """等元素出现/消失。
238
+
239
+ selector/xpath 走 page_wait(原生,最快);文本走 page_find 轮询;
240
+ role+name 走无障碍树轮询。label / placeholder 没有对应通道,请用 selector。
241
+ """
242
+ spec = self._spec_of(target)
243
+ native = wait_args(spec, state, timeout)
244
+ if native is not None:
245
+ self._raw('page_wait', native)
246
+ return
247
+ if spec.text:
248
+ self._poll_text(spec.text, state, timeout, poll_ms if poll_ms is not None else 300)
249
+ return
250
+ if spec.role and spec.name:
251
+ self._poll_snapshot(spec.name, state, timeout, poll_ms if poll_ms is not None else 500)
252
+ return
253
+ raise NotFoundError(
254
+ f'waitFor 不支持 {describe(spec)}:用 selector / xpath / getByText / getByRole 都能等,'
255
+ 'label 和 placeholder 请改写成 selector。'
256
+ )
257
+
258
+ def wait_for_text(self, text: str, state: str = 'appear', timeout: float = 10, poll_ms: int = 300) -> None:
259
+ """等页面上出现这段文字,用 Ctrl+F 的原生查找,不走 DOM。"""
260
+ self._poll_text(text, state, timeout, poll_ms)
261
+
262
+ def expect_text(self, text: str, state: str = 'appear', timeout: float = 10, poll_ms: int = 300) -> None:
263
+ """wait_for_text 的别名,读起来更像断言。"""
264
+ self.wait_for_text(text, state=state, timeout=timeout, poll_ms=poll_ms)
265
+
266
+ # ---------- 读取 ----------
267
+
268
+ def count(self, target: PageTarget) -> int:
269
+ spec = self._spec_of(target)
270
+ fields = _locate_fields(spec)
271
+ if fields is None:
272
+ raise NotFoundError(f'count 只支持 selector 或 xpath,收到 {describe(spec)}')
273
+ return _as_int(self.call('page_query', fields).get('total'))
274
+
275
+ def is_visible(self, target: PageTarget) -> bool:
276
+ spec = self._spec_of(target)
277
+ fields = _locate_fields(spec)
278
+ if fields is None:
279
+ raise NotFoundError(f'isVisible 只支持 selector 或 xpath,收到 {describe(spec)}')
280
+ matches = self.call('page_query', fields).get('matches') or []
281
+ return any(item.get('hittable') is True for item in matches)
282
+
283
+ def text_content(self, target: PageTarget) -> str:
284
+ spec = self._spec_of(target)
285
+ fields = _locate_fields(spec)
286
+ if fields is None:
287
+ raise NotFoundError(f'textContent 只支持 selector 或 xpath,收到 {describe(spec)}')
288
+ text = self.call('page_inspect', fields).get('text')
289
+ return '' if text is None else str(text)
290
+
291
+ def content(self, kind: str = 'dom') -> str:
292
+ """dom 是当前文档,response 是这次导航的原始 HTML。"""
293
+ html = self.call('page_source', {'kind': kind}).get('html')
294
+ return '' if html is None else str(html)
295
+
296
+ def snapshot(self) -> str:
297
+ """无障碍树,Agent 看页面主要靠它。"""
298
+ tree = self.call('page_snapshot', {}).get('snapshot')
299
+ return '' if tree is None else str(tree)
300
+
301
+ def evaluate(self, source: str, frame: Optional[str] = None) -> Any:
302
+ """在页面里执行 JS,返回值原样回来。
303
+
304
+ 只收 JS 源码:Python 函数没法序列化进页面,这一点和 Node 版不同。
305
+ """
306
+ if not isinstance(source, str):
307
+ raise TypeError('evaluate 只接受 JS 源码字符串;Python 函数没法送进页面执行')
308
+ args: Dict[str, Any] = {'source': source}
309
+ if frame is not None:
310
+ args['frame'] = frame
311
+ return self.call('page_script', args).get('value')
312
+
313
+ def console_logs(self, clear: bool = False, limit: int = 100) -> List[Dict[str, Any]]:
314
+ if clear:
315
+ self.call('page_console', {'action': 'clear'})
316
+ return []
317
+ messages = self.call('page_console', {'limit': limit}).get('messages')
318
+ return list(messages or [])
319
+
320
+ # ---------- 截图 ----------
321
+
322
+ def screenshot(
323
+ self,
324
+ path: Optional[str] = None,
325
+ target: Optional[PageTarget] = None,
326
+ clip: Optional[Mapping[str, Any]] = None,
327
+ grid: bool = False,
328
+ edge_only: bool = False,
329
+ ) -> bytes:
330
+ """返回图片字节,给了 path 就顺手写一份。
331
+
332
+ grid 默认关:App 默认会画坐标网格(给人用截图点位置),SDK 里那是噪点。
333
+ """
334
+ args: Dict[str, Any] = {'grid': bool(grid)}
335
+ if edge_only:
336
+ args['edgeOnly'] = True
337
+ if target is not None:
338
+ args.update(_locate_fields(self._spec_of(target)) or {})
339
+ if clip:
340
+ args.update(dict(clip))
341
+ result = self._raw('page_screenshot', args)
342
+ if result.image is None:
343
+ raise ToolError('page_screenshot', {'ok': False, 'error': '截图没有返回图片内容'})
344
+ if path:
345
+ Path(path).write_bytes(result.image.data)
346
+ return result.image.data
347
+
348
+ # ---------- 生命周期 ----------
349
+
350
+ def bring_to_front(self) -> None:
351
+ self._raw('tab_activate', {'tabId': self.id})
352
+
353
+ def close(self) -> None:
354
+ self._raw('tab_close', {'tabId': self.id})
355
+
356
+ # ---------- 内部 ----------
357
+
358
+ def _spec_of(self, target: PageTarget) -> LocatorSpec:
359
+ if isinstance(target, Locator):
360
+ return target.spec
361
+ return coerce_spec(target)
362
+
363
+ def _info(self) -> Dict[str, str]:
364
+ tabs = self._transport.call('tab_list', {}).data.get('tabs') or []
365
+ for tab in tabs:
366
+ if tab.get('id') == self.id:
367
+ return {'url': str(tab.get('url') or ''), 'title': str(tab.get('title') or '')}
368
+ raise NotFoundError(f'标签 {self.id} 已经不在了')
369
+
370
+ def _raw(self, tool: str, args: Mapping[str, Any], timeout: Optional[float] = None):
371
+ # tabId 放前面,这样显式传进来的 tabId 仍然能覆盖。
372
+ return self._transport.call(tool, {'tabId': self.id, **dict(args)}, timeout=timeout)
373
+
374
+ def _poll_text(self, text: str, state: str, timeout: float, poll_ms: int) -> None:
375
+ deadline = time.monotonic() + timeout
376
+ try:
377
+ while True:
378
+ found = self.call('page_find', {'text': text})
379
+ # page_find 返回 { matches, active };total 兜底兼容旧载荷
380
+ present = _as_int(found.get('matches', found.get('total'))) > 0
381
+ if present != (state == 'gone'):
382
+ return
383
+ if time.monotonic() > deadline:
384
+ raise NotFoundError(
385
+ f"等了 {timeout}s,页面上{'还' if state == 'gone' else '没'}出现「{text}」"
386
+ )
387
+ time.sleep(poll_ms / 1000.0)
388
+ finally:
389
+ # 原生查找会高亮,收尾一定要清掉。
390
+ try:
391
+ self.call('page_find', {'stop': True})
392
+ except BrowserPilotError:
393
+ pass
394
+
395
+ def _poll_snapshot(self, name: str, state: str, timeout: float, poll_ms: int) -> None:
396
+ """page_wait 不认 role,只能轮询无障碍树。"""
397
+ deadline = time.monotonic() + timeout
398
+ while True:
399
+ present = name in self.snapshot()
400
+ if present != (state == 'gone'):
401
+ return
402
+ if time.monotonic() > deadline:
403
+ raise NotFoundError(
404
+ f"等了 {timeout}s,无障碍树里{'还' if state == 'gone' else '没'}出现「{name}」"
405
+ )
406
+ time.sleep(poll_ms / 1000.0)