@jayyuen66/dsh-scrapling 0.1.16 → 0.2.0
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.
- package/CHANGELOG.md +73 -0
- package/README.md +160 -251
- package/README.zh-CN.md +226 -317
- package/THIRD_PARTY_NOTICES.md +54 -15
- package/bin/dsh-scrapling.mjs +13 -74
- package/client.js +6 -6
- package/cordis.patch.yml +1 -1
- package/docs/DETAIL.md +22 -22
- package/docs/DETAIL.zh.md +27 -27
- package/docs/images/architecture.svg +100 -0
- package/docs/images/architecture.zh.svg +99 -0
- package/docs/images/tool-selection.svg +88 -0
- package/docs/images/tool-selection.zh.svg +88 -0
- package/host.js +26 -45
- package/package.json +67 -62
- package/py/adapters.py +204 -57
- package/py/bridge.py +80 -8
- package/py/cancellation.py +56 -0
- package/py/crawl.py +1 -1
- package/py/document.py +128 -0
- package/py/documents-requirements.txt +1 -0
- package/py/extraction.py +2 -2
- package/py/media.py +4 -3
- package/py/runtime-requirements.txt +4 -3
- package/py/search.py +109 -24
- package/py/session_page.py +92 -24
- package/runtime-manifest.json +6 -0
package/py/search.py
CHANGED
|
@@ -2,12 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
Scrapling 本身不是搜索引擎;这里只负责拿 URL 列表,正文渲染仍由 Host 侧的
|
|
4
4
|
search provider 交给本 sidecar 的 fetch/render。每条后端都按各家**文档里的**
|
|
5
|
-
|
|
5
|
+
请求与响应形状实现。Tavily 与 Bing 在本机打过真实端点;其余后端只有文档形状
|
|
6
|
+
与夹具,未在真实端点验证。
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
from __future__ import annotations
|
|
9
10
|
|
|
10
|
-
|
|
11
|
+
import base64
|
|
12
|
+
import binascii
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
from urllib.parse import parse_qs, urlparse
|
|
16
|
+
|
|
17
|
+
import guard
|
|
18
|
+
from curl_cffi.requests import ProxySpec
|
|
11
19
|
|
|
12
20
|
DEFAULT_TAVILY_ENDPOINT = "https://api.tavily.com/search"
|
|
13
21
|
DEFAULT_BING_ENDPOINT = "https://www.bing.com/search"
|
|
@@ -27,6 +35,11 @@ TAVILY_MAX_RESULTS = 20
|
|
|
27
35
|
# `3 × timeout + 2s`,比协议层先到期的超时还长 —— 于是 SEARCH_TIMEOUT 永远走不到,
|
|
28
36
|
# 模型看到的是一条含义更模糊的协议层超时。显式传 1 让两层的预算对齐。
|
|
29
37
|
SEARCH_RETRIES = 1
|
|
38
|
+
_CJK_QUERY = re.compile(r"[\u3400-\u9fff]")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _proxies(url: str) -> "ProxySpec | None":
|
|
42
|
+
return cast("ProxySpec | None", guard.proxies_for(url))
|
|
30
43
|
|
|
31
44
|
|
|
32
45
|
class SearchError(ValueError):
|
|
@@ -45,6 +58,14 @@ def _positive_int(value: Any, field: str, default: int) -> int:
|
|
|
45
58
|
return value
|
|
46
59
|
|
|
47
60
|
|
|
61
|
+
def _offset(value: Any) -> int:
|
|
62
|
+
if value is None:
|
|
63
|
+
return 0
|
|
64
|
+
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
65
|
+
raise SearchError("BAD_ARGS", "offset must be a non-negative integer")
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
48
69
|
def _timeout(value: Any) -> float:
|
|
49
70
|
if value is None:
|
|
50
71
|
return DEFAULT_SEARCH_TIMEOUT_SECONDS
|
|
@@ -83,7 +104,7 @@ def _status_error(status: int, backend: str) -> SearchError | None:
|
|
|
83
104
|
return None
|
|
84
105
|
|
|
85
106
|
|
|
86
|
-
def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
107
|
+
def _tavily(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
87
108
|
key = args.get("apiKey")
|
|
88
109
|
if not isinstance(key, str) or not key:
|
|
89
110
|
raise SearchError(
|
|
@@ -99,11 +120,12 @@ def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
|
|
|
99
120
|
json={
|
|
100
121
|
"api_key": key,
|
|
101
122
|
"query": query,
|
|
102
|
-
"max_results": min(limit, TAVILY_MAX_RESULTS),
|
|
123
|
+
"max_results": min(limit + offset, TAVILY_MAX_RESULTS),
|
|
103
124
|
"search_depth": "basic",
|
|
104
125
|
},
|
|
105
126
|
timeout=timeout,
|
|
106
127
|
retries=SEARCH_RETRIES,
|
|
128
|
+
proxies=_proxies(endpoint),
|
|
107
129
|
)
|
|
108
130
|
except Exception as error: # noqa: BLE001 —— 只翻译成带码的失败,不回显请求体
|
|
109
131
|
raise _translate(error, "tavily") from None
|
|
@@ -115,20 +137,58 @@ def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
|
|
|
115
137
|
# 而非对象回包已经在 _json_body 那里判成 SEARCH_FAILED 了。
|
|
116
138
|
hits = _collect(
|
|
117
139
|
payload.get("results"),
|
|
118
|
-
limit=limit,
|
|
140
|
+
limit=limit + offset,
|
|
119
141
|
url_key="url",
|
|
120
142
|
title_key="title",
|
|
121
143
|
snippet_key="content",
|
|
144
|
+
summary_key="summary",
|
|
145
|
+
date_key="published_date",
|
|
122
146
|
)
|
|
123
|
-
return {"backend": "tavily", "hits": hits}
|
|
147
|
+
return {"backend": "tavily", "hits": hits[offset : offset + limit]}
|
|
124
148
|
|
|
125
149
|
|
|
126
|
-
def
|
|
150
|
+
def _bing_target(href: str) -> str:
|
|
151
|
+
"""解包 Bing 的 ck/a 跳板;只接受 Bing 自家主机与 http(s) 目标。"""
|
|
152
|
+
parts = urlparse(href)
|
|
153
|
+
host = (parts.hostname or "").lower()
|
|
154
|
+
if not (host == "bing.com" or host.endswith(".bing.com")) or parts.path != "/ck/a":
|
|
155
|
+
return href
|
|
156
|
+
token = parse_qs(parts.query).get("u", [""])[0]
|
|
157
|
+
if not token.startswith("a1"):
|
|
158
|
+
return href
|
|
159
|
+
encoded = token[2:]
|
|
160
|
+
try:
|
|
161
|
+
target = base64.b64decode(
|
|
162
|
+
encoded + "=" * (-len(encoded) % 4),
|
|
163
|
+
altchars=b"-_",
|
|
164
|
+
validate=True,
|
|
165
|
+
).decode("utf-8")
|
|
166
|
+
except ValueError, binascii.Error, UnicodeDecodeError:
|
|
167
|
+
return href
|
|
168
|
+
parsed = urlparse(target)
|
|
169
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.username or parsed.password:
|
|
170
|
+
return href
|
|
171
|
+
return target
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _bing(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
127
175
|
endpoint = _endpoint(args.get("bingEndpoint"), DEFAULT_BING_ENDPOINT, "bingEndpoint")
|
|
128
176
|
from scrapling.fetchers import Fetcher
|
|
129
177
|
|
|
178
|
+
params = {
|
|
179
|
+
"q": query,
|
|
180
|
+
"first": offset + 1,
|
|
181
|
+
"count": limit,
|
|
182
|
+
"setlang": "zh-hans" if _CJK_QUERY.search(query) else "en",
|
|
183
|
+
}
|
|
130
184
|
try:
|
|
131
|
-
response = Fetcher.get(
|
|
185
|
+
response = Fetcher.get(
|
|
186
|
+
endpoint,
|
|
187
|
+
params=params,
|
|
188
|
+
timeout=timeout,
|
|
189
|
+
retries=SEARCH_RETRIES,
|
|
190
|
+
proxies=_proxies(endpoint),
|
|
191
|
+
)
|
|
132
192
|
except Exception as error: # noqa: BLE001
|
|
133
193
|
raise _translate(error, "bing") from None
|
|
134
194
|
failed = _status_error(int(getattr(response, "status", 0)), "bing")
|
|
@@ -149,7 +209,7 @@ def _bing(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[
|
|
|
149
209
|
snippet_node = node.css(".b_caption p").first or node.css("p").first
|
|
150
210
|
hits.append(
|
|
151
211
|
{
|
|
152
|
-
"url": href,
|
|
212
|
+
"url": _bing_target(href),
|
|
153
213
|
"title": link.get_all_text(strip=True),
|
|
154
214
|
"snippet": snippet_node.get_all_text(strip=True) if snippet_node is not None else "",
|
|
155
215
|
}
|
|
@@ -191,9 +251,11 @@ def _collect(
|
|
|
191
251
|
url_key: str,
|
|
192
252
|
title_key: str,
|
|
193
253
|
snippet_key: str,
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
254
|
+
summary_key: str | None = None,
|
|
255
|
+
date_key: str | None = None,
|
|
256
|
+
) -> list[dict[str, Any]]:
|
|
257
|
+
"""把各家形状不同的结果表收成同一份 hits。"""
|
|
258
|
+
hits: list[dict[str, Any]] = []
|
|
197
259
|
if not isinstance(items, list):
|
|
198
260
|
return hits
|
|
199
261
|
for item in items:
|
|
@@ -204,11 +266,15 @@ def _collect(
|
|
|
204
266
|
continue
|
|
205
267
|
title = item.get(title_key)
|
|
206
268
|
snippet = item.get(snippet_key)
|
|
269
|
+
summary = item.get(summary_key) if summary_key is not None else None
|
|
270
|
+
published = item.get(date_key) if date_key is not None else None
|
|
207
271
|
hits.append(
|
|
208
272
|
{
|
|
209
273
|
"url": url,
|
|
210
274
|
"title": title if isinstance(title, str) else "",
|
|
211
275
|
"snippet": snippet if isinstance(snippet, str) else "",
|
|
276
|
+
**({"summary": summary} if isinstance(summary, str) and summary else {}),
|
|
277
|
+
**({"publishedAt": published} if isinstance(published, str) and published else {}),
|
|
212
278
|
}
|
|
213
279
|
)
|
|
214
280
|
if len(hits) >= limit:
|
|
@@ -226,7 +292,7 @@ def _nested(payload: dict[str, Any], *keys: str) -> Any:
|
|
|
226
292
|
return current
|
|
227
293
|
|
|
228
294
|
|
|
229
|
-
def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
295
|
+
def _brave(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
230
296
|
key = _require_key(args, "brave")
|
|
231
297
|
endpoint = _endpoint(args.get("braveEndpoint"), DEFAULT_BRAVE_ENDPOINT, "braveEndpoint")
|
|
232
298
|
from scrapling.fetchers import Fetcher
|
|
@@ -236,10 +302,11 @@ def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict
|
|
|
236
302
|
try:
|
|
237
303
|
response = Fetcher.get(
|
|
238
304
|
endpoint,
|
|
239
|
-
params={"q": query, "count": min(limit, BRAVE_MAX_COUNT)},
|
|
305
|
+
params={"q": query, "count": min(limit, BRAVE_MAX_COUNT), "offset": offset},
|
|
240
306
|
headers={"X-Subscription-Token": key, "Accept": "application/json"},
|
|
241
307
|
timeout=timeout,
|
|
242
308
|
retries=SEARCH_RETRIES,
|
|
309
|
+
proxies=_proxies(endpoint),
|
|
243
310
|
)
|
|
244
311
|
except Exception as error: # noqa: BLE001
|
|
245
312
|
raise _translate(error, "brave") from None
|
|
@@ -257,18 +324,21 @@ def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict
|
|
|
257
324
|
return {"backend": "brave", "hits": hits}
|
|
258
325
|
|
|
259
326
|
|
|
260
|
-
def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
327
|
+
def _serper(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
261
328
|
key = _require_key(args, "serper")
|
|
262
329
|
endpoint = _endpoint(args.get("serperEndpoint"), DEFAULT_SERPER_ENDPOINT, "serperEndpoint")
|
|
263
330
|
from scrapling.fetchers import Fetcher
|
|
264
331
|
|
|
332
|
+
page = offset // limit + 1
|
|
333
|
+
skip = offset % limit
|
|
265
334
|
try:
|
|
266
335
|
response = Fetcher.post(
|
|
267
336
|
endpoint,
|
|
268
|
-
json={"q": query, "num": limit},
|
|
337
|
+
json={"q": query, "num": limit + skip, "page": page},
|
|
269
338
|
headers={"X-API-KEY": key, "Content-Type": "application/json"},
|
|
270
339
|
timeout=timeout,
|
|
271
340
|
retries=SEARCH_RETRIES,
|
|
341
|
+
proxies=_proxies(endpoint),
|
|
272
342
|
)
|
|
273
343
|
except Exception as error: # noqa: BLE001
|
|
274
344
|
raise _translate(error, "serper") from None
|
|
@@ -278,12 +348,13 @@ def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
|
|
|
278
348
|
payload = _json_body(response, "serper")
|
|
279
349
|
hits = _collect(
|
|
280
350
|
payload.get("organic"),
|
|
281
|
-
limit=limit,
|
|
351
|
+
limit=limit + skip,
|
|
282
352
|
url_key="link",
|
|
283
353
|
title_key="title",
|
|
284
354
|
snippet_key="snippet",
|
|
355
|
+
date_key="date",
|
|
285
356
|
)
|
|
286
|
-
return {"backend": "serper", "hits": hits}
|
|
357
|
+
return {"backend": "serper", "hits": hits[skip : skip + limit]}
|
|
287
358
|
|
|
288
359
|
|
|
289
360
|
def _duckduckgo_target(href: str) -> str:
|
|
@@ -305,12 +376,18 @@ def _duckduckgo_target(href: str) -> str:
|
|
|
305
376
|
return urlunparse(parts)
|
|
306
377
|
|
|
307
378
|
|
|
308
|
-
def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
379
|
+
def _duckduckgo(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
309
380
|
endpoint = _endpoint(args.get("duckduckgoEndpoint"), DEFAULT_DUCKDUCKGO_ENDPOINT, "duckduckgoEndpoint")
|
|
310
381
|
from scrapling.fetchers import Fetcher
|
|
311
382
|
|
|
312
383
|
try:
|
|
313
|
-
response = Fetcher.get(
|
|
384
|
+
response = Fetcher.get(
|
|
385
|
+
endpoint,
|
|
386
|
+
params={"q": query, "s": offset},
|
|
387
|
+
timeout=timeout,
|
|
388
|
+
retries=SEARCH_RETRIES,
|
|
389
|
+
proxies=_proxies(endpoint),
|
|
390
|
+
)
|
|
314
391
|
except Exception as error: # noqa: BLE001
|
|
315
392
|
raise _translate(error, "duckduckgo") from None
|
|
316
393
|
failed = _status_error(int(getattr(response, "status", 0)), "duckduckgo")
|
|
@@ -344,7 +421,7 @@ def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) ->
|
|
|
344
421
|
return result
|
|
345
422
|
|
|
346
423
|
|
|
347
|
-
def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
424
|
+
def _searxng(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
|
|
348
425
|
endpoint = args.get("searxngEndpoint")
|
|
349
426
|
if not isinstance(endpoint, str) or not endpoint:
|
|
350
427
|
raise SearchError(
|
|
@@ -356,7 +433,13 @@ def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> di
|
|
|
356
433
|
from scrapling.fetchers import Fetcher
|
|
357
434
|
|
|
358
435
|
try:
|
|
359
|
-
response = Fetcher.get(
|
|
436
|
+
response = Fetcher.get(
|
|
437
|
+
url,
|
|
438
|
+
params={"q": query, "format": "json", "pageno": offset // limit + 1},
|
|
439
|
+
timeout=timeout,
|
|
440
|
+
retries=SEARCH_RETRIES,
|
|
441
|
+
proxies=_proxies(url),
|
|
442
|
+
)
|
|
360
443
|
except Exception as error: # noqa: BLE001
|
|
361
444
|
raise _translate(error, "searxng") from None
|
|
362
445
|
failed = _status_error(int(getattr(response, "status", 0)), "searxng")
|
|
@@ -369,6 +452,7 @@ def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> di
|
|
|
369
452
|
url_key="url",
|
|
370
453
|
title_key="title",
|
|
371
454
|
snippet_key="content",
|
|
455
|
+
date_key="publishedDate",
|
|
372
456
|
)
|
|
373
457
|
return {"backend": "searxng", "hits": hits}
|
|
374
458
|
|
|
@@ -390,11 +474,12 @@ def discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
390
474
|
if not isinstance(query, str) or not query.strip():
|
|
391
475
|
raise SearchError("BAD_ARGS", "query must be a non-empty string")
|
|
392
476
|
limit = _positive_int(args.get("maxResults"), "maxResults", DEFAULT_SEARCH_RESULTS)
|
|
477
|
+
offset = _offset(args.get("offset"))
|
|
393
478
|
timeout = _timeout(args.get("timeoutSeconds"))
|
|
394
479
|
key = args.get("apiKey")
|
|
395
480
|
resolved = backend
|
|
396
481
|
if backend == "auto":
|
|
397
|
-
#
|
|
482
|
+
# auto 只挑「部署真的配好了的」后端。公共引擎回退
|
|
398
483
|
# (Bing)默认关闭,要部署显式打开 searchPublicFallback;否则这里必须报
|
|
399
484
|
# SEARCH_BACKEND_MISSING,而不是擅自把查询发给公共站点。
|
|
400
485
|
searxng_endpoint = args.get("searxngEndpoint")
|
|
@@ -420,4 +505,4 @@ def discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
420
505
|
"duckduckgo": _duckduckgo,
|
|
421
506
|
"searxng": _searxng,
|
|
422
507
|
}
|
|
423
|
-
return handlers[resolved](args, query.strip(), limit, timeout)
|
|
508
|
+
return handlers[resolved](args, query.strip(), limit, offset, timeout)
|
package/py/session_page.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""会话当前页的读取。只碰浏览器会话的 page pool,不新建浏览器。"""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from typing import Any
|
|
6
6
|
|
|
7
|
+
from cancellation import RequestCancelled, raise_if_cancelled
|
|
8
|
+
|
|
7
9
|
|
|
8
10
|
def _adapter_error(code: str, message: str, *, details: dict[str, Any] | None = None) -> Exception:
|
|
9
11
|
from adapters import AdapterError
|
|
@@ -28,9 +30,12 @@ _ACTION_TYPES = frozenset(
|
|
|
28
30
|
"wait_time",
|
|
29
31
|
"wait_element",
|
|
30
32
|
"wait_load",
|
|
33
|
+
"drag",
|
|
31
34
|
}
|
|
32
35
|
)
|
|
33
36
|
_SELECTOR_ACTIONS = frozenset({"click", "textbox", "checkbox", "radio", "combobox", "wait_element"})
|
|
37
|
+
_SNAPSHOT_TYPES = frozenset({"text", "aria"})
|
|
38
|
+
_DRAG_COORDINATES = ("fromX", "fromY", "toX", "toY")
|
|
34
39
|
_ELEMENT_STATES = frozenset({"attached", "detached", "hidden", "visible"})
|
|
35
40
|
_LOAD_STATES = frozenset({"load", "domcontentloaded", "networkidle"})
|
|
36
41
|
|
|
@@ -92,8 +97,8 @@ def _number(value: Any) -> bool:
|
|
|
92
97
|
"""是不是一个真数字:`bool` 是 `int` 的子类,`True` 会被 `float()` 静默变成 1.0。
|
|
93
98
|
|
|
94
99
|
坐标与滚轮位移用这一条判据。传 `true` / `false` 是调用方明显的传参错误,静默成 1.0 / 0.0
|
|
95
|
-
等于替它做了一次带副作用的鼠标位移。同文件对 `wait_time.ms`
|
|
96
|
-
(`isinstance(ms, bool)
|
|
100
|
+
等于替它做了一次带副作用的鼠标位移。同文件对 `wait_time.ms` 也显式排除 `bool`
|
|
101
|
+
(`isinstance(ms, bool)`),两处判据同源。
|
|
97
102
|
"""
|
|
98
103
|
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
99
104
|
|
|
@@ -107,41 +112,67 @@ def read_current_page(
|
|
|
107
112
|
max_content_chars: int,
|
|
108
113
|
include_metadata: bool,
|
|
109
114
|
strip_inline_images: bool,
|
|
115
|
+
snapshot_type: str = "text",
|
|
110
116
|
) -> dict[str, Any]:
|
|
111
|
-
"""
|
|
112
|
-
|
|
113
|
-
页面池把「没有页」与「页都被占用」分成两件事:前者是还没抓过,后者是别的请求
|
|
114
|
-
正在用这一页。两者对模型要采取的行动不同,所以不能合并成一个空正文。
|
|
115
|
-
"""
|
|
116
|
-
from adapters import _fake_response, to_payload
|
|
117
|
+
"""读当前就绪页的正文或 ARIA 快照;没有页或页不可用时给出明确错误码。"""
|
|
118
|
+
from adapters import _fake_response, clip, to_payload
|
|
117
119
|
|
|
120
|
+
if snapshot_type not in _SNAPSHOT_TYPES:
|
|
121
|
+
raise _adapter_error("BAD_ARGS", "snapshotType must be text or aria")
|
|
122
|
+
raise_if_cancelled()
|
|
118
123
|
page_info = _ready_page(session)
|
|
119
124
|
page = page_info.page
|
|
125
|
+
payload: dict[str, Any] | None = None
|
|
120
126
|
try:
|
|
121
127
|
if page.is_closed():
|
|
122
128
|
raise _closed_page_error()
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
129
|
+
if snapshot_type == "aria":
|
|
130
|
+
try:
|
|
131
|
+
raw = (page.locator(css_selector) if css_selector else page).aria_snapshot(mode="ai")
|
|
132
|
+
except Exception as error:
|
|
133
|
+
if page.is_closed():
|
|
134
|
+
raise _closed_page_error() from error
|
|
135
|
+
raise _adapter_error(
|
|
136
|
+
"SESSION_READ_FAILED",
|
|
137
|
+
f"ARIA snapshot failed: {type(error).__name__}: {error}",
|
|
138
|
+
) from error
|
|
139
|
+
raise_if_cancelled()
|
|
140
|
+
content, truncated = clip(str(raw), max_content_chars)
|
|
141
|
+
url, title = _page_identity(page)
|
|
142
|
+
else:
|
|
143
|
+
try:
|
|
144
|
+
html = page.content()
|
|
145
|
+
except Exception as error: # 读到一半页被关掉/崩溃,归成「这一页没了」
|
|
146
|
+
raise _closed_page_error() from error
|
|
147
|
+
raise_if_cancelled()
|
|
148
|
+
url, title = _page_identity(page)
|
|
149
|
+
response = _fake_response(str(html), url, 200)
|
|
150
|
+
payload = to_payload(
|
|
151
|
+
response,
|
|
152
|
+
extraction_type=extraction_type,
|
|
153
|
+
css_selector=css_selector,
|
|
154
|
+
main_content_only=main_content_only,
|
|
155
|
+
max_content_chars=max_content_chars,
|
|
156
|
+
strip_inline_images=strip_inline_images,
|
|
157
|
+
include_metadata=include_metadata,
|
|
158
|
+
)
|
|
138
159
|
finally:
|
|
139
160
|
_finish_page(session.page_pool, page_info)
|
|
161
|
+
if payload is None:
|
|
162
|
+
return {
|
|
163
|
+
"url": url,
|
|
164
|
+
"title": str(title),
|
|
165
|
+
"content": content,
|
|
166
|
+
"truncated": truncated,
|
|
167
|
+
"snapshotType": "aria",
|
|
168
|
+
"notice": "the page accessibility tree was read from the session's current DOM, not fetched again",
|
|
169
|
+
}
|
|
140
170
|
return {
|
|
141
171
|
"url": payload["url"],
|
|
142
172
|
"title": str(title),
|
|
143
173
|
"content": payload["content"],
|
|
144
174
|
"truncated": payload["truncated"],
|
|
175
|
+
"snapshotType": "text",
|
|
145
176
|
"notice": "the page was read from the session's current DOM, not fetched again",
|
|
146
177
|
**({"metadata": payload["metadata"]} if "metadata" in payload else {}),
|
|
147
178
|
}
|
|
@@ -166,12 +197,32 @@ def _has_target(action: dict[str, Any]) -> bool:
|
|
|
166
197
|
return isinstance(target, str) and bool(target)
|
|
167
198
|
|
|
168
199
|
|
|
200
|
+
def _drag_selectors(action: dict[str, Any]) -> bool:
|
|
201
|
+
return "from" in action or "to" in action
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _perform_drag(page: Any, action: dict[str, Any], timeout_ms: int) -> None:
|
|
205
|
+
if _drag_selectors(action):
|
|
206
|
+
page.locator(action["from"]).drag_to(page.locator(action["to"]), timeout=timeout_ms)
|
|
207
|
+
return
|
|
208
|
+
mouse = page.mouse
|
|
209
|
+
mouse.move(float(action["fromX"]), float(action["fromY"]))
|
|
210
|
+
mouse.down()
|
|
211
|
+
try:
|
|
212
|
+
mouse.move(float(action["toX"]), float(action["toY"]), steps=10)
|
|
213
|
+
finally:
|
|
214
|
+
mouse.up()
|
|
215
|
+
|
|
216
|
+
|
|
169
217
|
def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> Any:
|
|
170
218
|
"""执行一个已校验的动作;dialog 注册的处理器会返回,由调用方在批次结束时摘掉。"""
|
|
171
219
|
kind = str(action["type"])
|
|
172
220
|
if kind == "wait_time":
|
|
173
221
|
page.wait_for_timeout(int(action["ms"]))
|
|
174
222
|
return None
|
|
223
|
+
if kind == "drag":
|
|
224
|
+
_perform_drag(page, action, timeout_ms)
|
|
225
|
+
return None
|
|
175
226
|
if kind == "wait_load":
|
|
176
227
|
page.wait_for_load_state(str(action.get("state", "load")), timeout=timeout_ms)
|
|
177
228
|
return None
|
|
@@ -248,6 +299,16 @@ def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
|
|
|
248
299
|
raise _adapter_error("ACTION_INVALID", "move needs a non-empty target selector or x/y coordinates")
|
|
249
300
|
if kind == "wheel" and (not _number(action.get("deltaX")) or not _number(action.get("deltaY"))):
|
|
250
301
|
raise _adapter_error("ACTION_INVALID", "wheel needs numeric deltaX and deltaY")
|
|
302
|
+
if kind == "drag":
|
|
303
|
+
has_selectors = _drag_selectors(action)
|
|
304
|
+
has_coordinates = any(key in action for key in _DRAG_COORDINATES)
|
|
305
|
+
if has_selectors and has_coordinates:
|
|
306
|
+
raise _adapter_error("ACTION_INVALID", "drag cannot mix selectors and coordinates")
|
|
307
|
+
if has_selectors:
|
|
308
|
+
if not all(isinstance(action.get(key), str) and action[key] for key in ("from", "to")):
|
|
309
|
+
raise _adapter_error("ACTION_INVALID", "drag needs non-empty from/to selectors")
|
|
310
|
+
elif not all(_number(action.get(key)) for key in _DRAG_COORDINATES):
|
|
311
|
+
raise _adapter_error("ACTION_INVALID", "drag needs fromX/fromY/toX/toY coordinates")
|
|
251
312
|
if kind == "wait_time":
|
|
252
313
|
ms = action.get("ms")
|
|
253
314
|
if not isinstance(ms, int) or isinstance(ms, bool) or ms < 0:
|
|
@@ -311,6 +372,7 @@ def run_actions(
|
|
|
311
372
|
) -> dict[str, Any]:
|
|
312
373
|
"""按顺序执行结构化动作;首个失败停止并点名下标。"""
|
|
313
374
|
prepared = _validate_actions(actions, max_actions)
|
|
375
|
+
raise_if_cancelled()
|
|
314
376
|
page_info = _ready_page(session)
|
|
315
377
|
page = page_info.page
|
|
316
378
|
completed = 0
|
|
@@ -320,12 +382,17 @@ def run_actions(
|
|
|
320
382
|
raise _closed_page_error()
|
|
321
383
|
for index, action in enumerate(prepared, start=1):
|
|
322
384
|
try:
|
|
385
|
+
raise_if_cancelled()
|
|
323
386
|
handler = _perform(page, action, timeout_ms)
|
|
324
387
|
if handler is not None:
|
|
325
388
|
dialog_handlers.append(handler)
|
|
389
|
+
raise_if_cancelled()
|
|
326
390
|
completed = index
|
|
327
391
|
if slowly:
|
|
328
392
|
page.wait_for_timeout(100)
|
|
393
|
+
raise_if_cancelled()
|
|
394
|
+
except RequestCancelled:
|
|
395
|
+
raise
|
|
329
396
|
except Exception as error:
|
|
330
397
|
# 慢速间隔也在这一层里:页在动作之间被关掉时同样按 ACTION_FAILED 点名下标,
|
|
331
398
|
# 而不是把裸异常漏给宿主。
|
|
@@ -334,6 +401,7 @@ def run_actions(
|
|
|
334
401
|
f"action {index} ({action['type']}) failed: {type(error).__name__}: {error}",
|
|
335
402
|
details={"actionIndex": index},
|
|
336
403
|
) from error
|
|
404
|
+
raise_if_cancelled()
|
|
337
405
|
# 终页信息在 finally 之外读:动作全做成了才走这里,而这两项各自兜底(一次关窗或页崩溃
|
|
338
406
|
# 不该把已经完成的批次报成内部异常)。
|
|
339
407
|
url, title = _page_identity(page)
|
package/runtime-manifest.json
CHANGED
|
@@ -8,6 +8,12 @@
|
|
|
8
8
|
"sha256": "226d696642a8a53d03b4d5b255b1c319b1575a6d44bd723a953c9f507755e36a",
|
|
9
9
|
"sizeBytes": 26834117
|
|
10
10
|
},
|
|
11
|
+
"documents": {
|
|
12
|
+
"requirements": "py/documents-requirements.txt",
|
|
13
|
+
"distribution": "pypdf",
|
|
14
|
+
"version": "7.2.0",
|
|
15
|
+
"sha256": "de0b61a9023cb7ea8347d44e17d715f9064e91c7507d3646f86b282cd696e795"
|
|
16
|
+
},
|
|
11
17
|
"unsupported": {
|
|
12
18
|
"darwin-x64": "not verified on this host",
|
|
13
19
|
"linux-x64": "not verified on this host",
|