@jayyuen66/dsh-scrapling 0.1.16 → 0.1.17
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 +17 -0
- package/README.md +43 -19
- package/README.zh-CN.md +44 -20
- package/THIRD_PARTY_NOTICES.md +3 -1
- package/bin/dsh-scrapling.mjs +71 -71
- package/client.js +1 -1
- package/cordis.patch.yml +1 -1
- package/docs/DETAIL.md +16 -7
- package/docs/DETAIL.zh.md +16 -7
- package/host.js +25 -21
- package/package.json +4 -1
- package/py/adapters.py +190 -44
- package/py/bridge.py +77 -5
- package/py/cancellation.py +56 -0
- package/py/document.py +128 -0
- package/py/documents-requirements.txt +1 -0
- package/py/media.py +3 -2
- package/py/runtime-requirements.txt +1 -0
- package/py/search.py +106 -22
- package/py/session_page.py +90 -22
- package/runtime-manifest.json +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jayyuen66/dsh-scrapling",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.17",
|
|
4
4
|
"description": "Scrapling 网页抓取插件(dsh):静态/浏览器抓取 + CSS/XPath 结构化抽取 + 选择器自愈 + capture_xhr 与会话网络历史 + 登录态存取 + Spider 爬虫,由常驻 Python 进程驱动。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -38,15 +38,18 @@
|
|
|
38
38
|
"runtime-manifest.json",
|
|
39
39
|
"py/crawl.py",
|
|
40
40
|
"py/bridge.py",
|
|
41
|
+
"py/cancellation.py",
|
|
41
42
|
"py/adapters.py",
|
|
42
43
|
"py/guard.py",
|
|
43
44
|
"py/extraction.py",
|
|
44
45
|
"py/search.py",
|
|
45
46
|
"py/session_page.py",
|
|
46
47
|
"py/media.py",
|
|
48
|
+
"py/document.py",
|
|
47
49
|
"py/redact.py",
|
|
48
50
|
"py/redis_storage.py",
|
|
49
51
|
"py/runtime-requirements.txt",
|
|
52
|
+
"py/documents-requirements.txt",
|
|
50
53
|
"CHANGELOG.md",
|
|
51
54
|
"THIRD_PARTY_NOTICES.md"
|
|
52
55
|
],
|
package/py/adapters.py
CHANGED
|
@@ -22,6 +22,7 @@ from __future__ import annotations
|
|
|
22
22
|
import codecs
|
|
23
23
|
import concurrent.futures
|
|
24
24
|
import contextlib
|
|
25
|
+
import contextvars
|
|
25
26
|
import json
|
|
26
27
|
import queue
|
|
27
28
|
import re
|
|
@@ -31,11 +32,14 @@ import uuid
|
|
|
31
32
|
from datetime import datetime, timezone
|
|
32
33
|
from pathlib import Path
|
|
33
34
|
from typing import Any, Callable, NamedTuple
|
|
35
|
+
from urllib.parse import urlparse
|
|
34
36
|
|
|
37
|
+
import document
|
|
35
38
|
import extraction
|
|
36
39
|
import guard
|
|
37
40
|
import media
|
|
38
41
|
import search
|
|
42
|
+
from cancellation import RequestCancelled, raise_if_cancelled
|
|
39
43
|
from redact import redact_url_secrets
|
|
40
44
|
|
|
41
45
|
# Scrapling 缺失时不要让整个 sidecar 起不来:桥接层会把它报成能力缺失,
|
|
@@ -52,10 +56,13 @@ DEFAULT_EXTRACTION = "markdown"
|
|
|
52
56
|
DEFAULT_TIMEOUT_SECONDS = 120.0
|
|
53
57
|
DEFAULT_TIMEOUT_MS = 30_000
|
|
54
58
|
DEFAULT_MAX_CONTENT_CHARS = 200_000
|
|
55
|
-
#
|
|
56
|
-
# 量级,而这份摘要是给模型看的 ——
|
|
59
|
+
# 一次读网络历史的条目数、单条正文与总正文三条上限。上游为每条响应体存下的是 1 MiB
|
|
60
|
+
# 量级,而这份摘要是给模型看的 —— 三条预算都由本包定,不由上游存了多少决定。
|
|
57
61
|
DEFAULT_NETWORK_ENTRIES = 50
|
|
58
|
-
|
|
62
|
+
NETWORK_MAX_ENTRIES = 200
|
|
63
|
+
NETWORK_MAX_BODY_CHARS = 20_000
|
|
64
|
+
NETWORK_MAX_TOTAL_BODY_CHARS = 120_000
|
|
65
|
+
DEFAULT_NETWORK_BODY_CHARS = NETWORK_MAX_BODY_CHARS
|
|
59
66
|
EXTRACTION_TYPES = ("markdown", "html", "text", "json")
|
|
60
67
|
# adaptive 指纹库的文件名。**相对路径**:bridge 由宿主以部署侧的 dataDir 为工作目录拉起
|
|
61
68
|
# (见 host.ts 的 sidecar env),相对路径正好把库落进 dataDir —— Scrapling 自己的默认值
|
|
@@ -160,25 +167,30 @@ def _safe_headers(headers: Any) -> dict[str, str]:
|
|
|
160
167
|
return {str(key): str(value) for key, value in headers.items() if str(key).lower() not in _SENSITIVE_HEADERS}
|
|
161
168
|
|
|
162
169
|
|
|
163
|
-
def
|
|
170
|
+
def _network_summary_with_count(
|
|
164
171
|
network: Any, # 上游的 NetworkRecorder
|
|
165
172
|
*,
|
|
166
173
|
query: _NetworkQuery,
|
|
167
|
-
) -> list[dict[str, Any]]:
|
|
168
|
-
"""
|
|
174
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
175
|
+
"""把会话网络历史压成给模型看的条目,并独立报告过滤后的记录数。
|
|
169
176
|
|
|
170
177
|
只取 XHR/fetch 与 HTTP 错误(``include_static=False``):这条路径的用途是「页面数据来自
|
|
171
178
|
接口而不是 DOM 时,找到那个接口」,静态资源只会把列表淹掉。
|
|
172
179
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
180
|
+
``count`` 在 ``networkLimit`` 与逐条投影之前计算:上游 ``NetworkRecorder.search`` 的
|
|
181
|
+
``limit=None`` 返回全部过滤结果,因此单条投影失败也不会把总数一起减掉。
|
|
182
|
+
|
|
183
|
+
正文只在显式要求时回传,并按 ``max_body_chars`` 逐条截断;所有条目的正文字符总数另受
|
|
184
|
+
``NETWORK_MAX_TOTAL_BODY_CHARS`` 约束。上游为每条响应体设了 1 MiB、会话总量 20 MiB 的
|
|
185
|
+
硬上限,那几十倍于模型预算的量级不该由「上游记了什么」决定「模型看见什么」。没存下正文时
|
|
186
|
+
上游会在 ``meta['body_note']`` 里写原因,一并带出去,这样「这条接口没正文」与「这个接口
|
|
187
|
+
本来就空」不是同一件事。
|
|
177
188
|
|
|
178
189
|
URL 里的凭据型查询参数在这一层就脱敏:这份摘要是给模型看的,而模型用不上一个
|
|
179
190
|
access token 却会把整条 URL 原样复述出去。
|
|
180
191
|
"""
|
|
181
192
|
summary: list[dict[str, Any]] = []
|
|
193
|
+
total_body_chars = 0
|
|
182
194
|
try:
|
|
183
195
|
if query.request_id is not None:
|
|
184
196
|
record = network.get(query.request_id)
|
|
@@ -190,12 +202,13 @@ def _network_summary(
|
|
|
190
202
|
resource_type=query.resource_type,
|
|
191
203
|
status=query.status,
|
|
192
204
|
after_id=query.after_id,
|
|
193
|
-
limit=
|
|
205
|
+
limit=None,
|
|
194
206
|
include_static=query.include_static,
|
|
195
207
|
)
|
|
196
208
|
except Exception: # noqa: BLE001 —— 记录器未启用或上游改了口径:当成「没有历史」
|
|
197
|
-
return summary
|
|
198
|
-
|
|
209
|
+
return summary, 0
|
|
210
|
+
count = len(records)
|
|
211
|
+
for item in records[: query.limit]:
|
|
199
212
|
try:
|
|
200
213
|
meta = item.meta if isinstance(item.meta, dict) else {}
|
|
201
214
|
body = item.body
|
|
@@ -217,15 +230,30 @@ def _network_summary(
|
|
|
217
230
|
entry["bodyNote"] = note
|
|
218
231
|
elif query.include_body:
|
|
219
232
|
text = body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body)
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
233
|
+
remaining = NETWORK_MAX_TOTAL_BODY_CHARS - total_body_chars
|
|
234
|
+
if remaining == 0:
|
|
235
|
+
entry["body"] = ""
|
|
223
236
|
entry["bodyTruncated"] = True
|
|
237
|
+
else:
|
|
238
|
+
clipped, truncated = clip(text, min(query.body_chars, remaining))
|
|
239
|
+
entry["body"] = clipped
|
|
240
|
+
total_body_chars += len(clipped)
|
|
241
|
+
if truncated:
|
|
242
|
+
entry["bodyTruncated"] = True
|
|
224
243
|
summary.append(entry)
|
|
225
244
|
# 单条摘要失败不该拖垮整次读取;继续处理下一条。
|
|
226
245
|
except Exception: # noqa: BLE001, S112 # nosec B112
|
|
227
246
|
continue
|
|
228
|
-
return summary
|
|
247
|
+
return summary, count
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _network_summary(
|
|
251
|
+
network: Any, # 上游的 NetworkRecorder
|
|
252
|
+
*,
|
|
253
|
+
query: _NetworkQuery,
|
|
254
|
+
) -> list[dict[str, Any]]:
|
|
255
|
+
"""只返回投影后的条目;一次性 capture 不需要过滤后的总数。"""
|
|
256
|
+
return _network_summary_with_count(network, query=query)[0]
|
|
229
257
|
|
|
230
258
|
|
|
231
259
|
def _extraction(args: dict[str, Any]) -> tuple[str, str | None, bool, int]:
|
|
@@ -418,6 +446,7 @@ def to_payload(
|
|
|
418
446
|
文本照旧剥 data URI(内联图片对模型不可读,还会白吃 ``maxContentChars`` 的额度)并受
|
|
419
447
|
同一个 ``maxContentChars`` 封顶——与 html/text/markdown 三条路径同一套收口(spec:363)。
|
|
420
448
|
"""
|
|
449
|
+
raise_if_cancelled()
|
|
421
450
|
if extraction_type == "json":
|
|
422
451
|
try:
|
|
423
452
|
parsed = response.json()
|
|
@@ -464,6 +493,7 @@ def to_payload(
|
|
|
464
493
|
}
|
|
465
494
|
if include_metadata:
|
|
466
495
|
payload["metadata"] = _response_metadata(response, redirects)
|
|
496
|
+
raise_if_cancelled()
|
|
467
497
|
return payload
|
|
468
498
|
|
|
469
499
|
|
|
@@ -671,6 +701,7 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
671
701
|
allowed, reason = guard.url_allowed(url)
|
|
672
702
|
if not allowed:
|
|
673
703
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
704
|
+
raise_if_cancelled()
|
|
674
705
|
try:
|
|
675
706
|
response = getattr(Fetcher, method.lower())(url, **params)
|
|
676
707
|
except Exception as error:
|
|
@@ -787,11 +818,8 @@ SESSION_ONLY_KEYS = frozenset(
|
|
|
787
818
|
# 与模型入参走同一条通道而它承载的是**部署表态**:类型错了静默生效比报错更糟(例如
|
|
788
819
|
# maxRecordedRequests 收到字符串,上游会拿它当容量直接炸会话构造)。
|
|
789
820
|
#
|
|
790
|
-
#
|
|
791
|
-
#
|
|
792
|
-
# 「cdp_url and new_context require RemoteSession」那条),而本包没有远端会话模式。
|
|
793
|
-
# 递过去在 0.5 上能用、在 0.5.1 上炸会话构造,等于让同一条文档范围 `>=0.5,<0.6` 里
|
|
794
|
-
# 的两个版本行为分叉,所以这个旋钮整体撤掉。
|
|
821
|
+
# CDP 端点不在这张表里:它只属于 RemoteSession 的构造参数,递给 StealthySession
|
|
822
|
+
# 会被上游明确拒绝。remote 分支在 _make_session 里单独读取并校验部署值。
|
|
795
823
|
_DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
|
|
796
824
|
("browserExecutablePath", "executable_path", str),
|
|
797
825
|
("browserInitScript", "init_script", str),
|
|
@@ -954,6 +982,7 @@ def render(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
954
982
|
|
|
955
983
|
params = _browser_params(args, url)
|
|
956
984
|
params["page_setup"] = page_setup
|
|
985
|
+
raise_if_cancelled()
|
|
957
986
|
response = StealthyFetcher.fetch(url, **params)
|
|
958
987
|
return to_payload(
|
|
959
988
|
response,
|
|
@@ -985,6 +1014,9 @@ class _NetworkQuery(NamedTuple):
|
|
|
985
1014
|
def _network_read(args: dict[str, Any]) -> _NetworkQuery:
|
|
986
1015
|
"""抽出「读网络历史」的过滤与投影参数并校验。
|
|
987
1016
|
|
|
1017
|
+
条目数与单条正文只压上限,不把 0、负数或非整数静默改成合法值;总正文在
|
|
1018
|
+
``_network_summary`` 逐条累计。
|
|
1019
|
+
|
|
988
1020
|
:param args: 协议参数
|
|
989
1021
|
:returns: 归一后的查询参数
|
|
990
1022
|
"""
|
|
@@ -1005,9 +1037,15 @@ def _network_read(args: dict[str, Any]) -> _NetworkQuery:
|
|
|
1005
1037
|
raise AdapterError("BAD_ARGS", "requestId must be a positive integer or null")
|
|
1006
1038
|
return _NetworkQuery(
|
|
1007
1039
|
pattern=_url_pattern(args),
|
|
1008
|
-
limit=
|
|
1040
|
+
limit=min(
|
|
1041
|
+
_positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
|
|
1042
|
+
NETWORK_MAX_ENTRIES,
|
|
1043
|
+
),
|
|
1009
1044
|
include_body=bool(args.get("includeBody", False)),
|
|
1010
|
-
body_chars=
|
|
1045
|
+
body_chars=min(
|
|
1046
|
+
_positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
|
|
1047
|
+
NETWORK_MAX_BODY_CHARS,
|
|
1048
|
+
),
|
|
1011
1049
|
method=method.upper() if isinstance(method, str) else None,
|
|
1012
1050
|
status=status,
|
|
1013
1051
|
resource_type=resource_type,
|
|
@@ -1036,6 +1074,7 @@ def _capture_once(
|
|
|
1036
1074
|
"""
|
|
1037
1075
|
from scrapling.fetchers import StealthySession
|
|
1038
1076
|
|
|
1077
|
+
raise_if_cancelled()
|
|
1039
1078
|
session_params = _session_browser_params(args)
|
|
1040
1079
|
# 与 _make_session 对齐:浏览器会话的代理只能在构造期给,而 _session_browser_params
|
|
1041
1080
|
# 按 SESSION_ONLY_KEYS 把它连同 block_webrtc 一起过滤掉了。不在这里补,配了代理的
|
|
@@ -1053,8 +1092,11 @@ def _capture_once(
|
|
|
1053
1092
|
session = StealthySession(**session_params)
|
|
1054
1093
|
try:
|
|
1055
1094
|
session.start()
|
|
1095
|
+
raise_if_cancelled()
|
|
1056
1096
|
response = session.fetch(url, **fetch_params)
|
|
1097
|
+
raise_if_cancelled()
|
|
1057
1098
|
records = _network_summary(session.network, query=query)
|
|
1099
|
+
raise_if_cancelled()
|
|
1058
1100
|
finally:
|
|
1059
1101
|
# 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
|
|
1060
1102
|
with contextlib.suppress(Exception):
|
|
@@ -1148,6 +1190,8 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1148
1190
|
"""对已有 HTML 做选择,返回命中文本、属性或多字段行。"""
|
|
1149
1191
|
from scrapling.parser import Selector
|
|
1150
1192
|
|
|
1193
|
+
raise_if_cancelled()
|
|
1194
|
+
|
|
1151
1195
|
html = args.get("html")
|
|
1152
1196
|
if not isinstance(html, str):
|
|
1153
1197
|
raise AdapterError("BAD_ARGS", "html must be a string")
|
|
@@ -1251,6 +1295,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1251
1295
|
page = Selector(html, url=url or "")
|
|
1252
1296
|
nodes, notice = query_nodes(page, use_adaptive=False)
|
|
1253
1297
|
|
|
1298
|
+
raise_if_cancelled()
|
|
1254
1299
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
1255
1300
|
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
1256
1301
|
include_attributes = bool(args.get("includeAttributes", False))
|
|
@@ -1261,6 +1306,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1261
1306
|
if fields is not None:
|
|
1262
1307
|
if not isinstance(fields, dict):
|
|
1263
1308
|
raise AdapterError("BAD_ARGS", "fields must be an object or null")
|
|
1309
|
+
raise_if_cancelled()
|
|
1264
1310
|
try:
|
|
1265
1311
|
rows, fields_truncated = extraction.collect_fields(
|
|
1266
1312
|
list(nodes)[:limit],
|
|
@@ -1271,6 +1317,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1271
1317
|
)
|
|
1272
1318
|
except ValueError as error:
|
|
1273
1319
|
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1320
|
+
raise_if_cancelled()
|
|
1274
1321
|
return {
|
|
1275
1322
|
"count": len(nodes),
|
|
1276
1323
|
"truncated": fields_truncated or len(nodes) > limit,
|
|
@@ -1282,6 +1329,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1282
1329
|
spent = 0
|
|
1283
1330
|
clipped = False
|
|
1284
1331
|
for node in nodes:
|
|
1332
|
+
raise_if_cancelled()
|
|
1285
1333
|
if len(matches) >= limit:
|
|
1286
1334
|
break
|
|
1287
1335
|
item = extraction.serialize_match(
|
|
@@ -1376,13 +1424,24 @@ def _websocket_guard_capability() -> bool:
|
|
|
1376
1424
|
return guard.websocket_guard_supported(Page)
|
|
1377
1425
|
|
|
1378
1426
|
|
|
1427
|
+
def _remote_session_available() -> bool:
|
|
1428
|
+
"""当前 Scrapling 是否导出 RemoteSession;不连接端点也能判断。"""
|
|
1429
|
+
try:
|
|
1430
|
+
from scrapling.fetchers import RemoteSession
|
|
1431
|
+
except ImportError:
|
|
1432
|
+
return False
|
|
1433
|
+
return callable(RemoteSession)
|
|
1434
|
+
|
|
1435
|
+
|
|
1379
1436
|
def capabilities() -> dict[str, Any]:
|
|
1380
1437
|
"""报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
|
|
1381
1438
|
report: dict[str, Any] = {
|
|
1382
1439
|
"scrapling": SCRAPLING_AVAILABLE,
|
|
1383
1440
|
"static": SCRAPLING_AVAILABLE,
|
|
1384
1441
|
"extract": SCRAPLING_AVAILABLE,
|
|
1442
|
+
"documents": document.available(),
|
|
1385
1443
|
"browser": False,
|
|
1444
|
+
"remote": False,
|
|
1386
1445
|
# 写方法这一档**与 scrapling 在不在无关**:它是部署表态,而排障的人得能一眼看出
|
|
1387
1446
|
# 「这台到底许不许写」,而不是等到发 POST 被拒才发现环境里少一个变量。
|
|
1388
1447
|
"writeMethods": guard.ALLOW_WRITE_METHODS,
|
|
@@ -1393,6 +1452,7 @@ def capabilities() -> dict[str, Any]:
|
|
|
1393
1452
|
# 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
|
|
1394
1453
|
# 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的规则已经没有第二个引擎可标。
|
|
1395
1454
|
report["browser"] = _probe_browser("patchright.sync_api")
|
|
1455
|
+
report["remote"] = _remote_session_available()
|
|
1396
1456
|
# 浏览器守卫覆盖面的那一半(WebSocket 握手)在这里报出:拦不住时 install 只会往 stderr
|
|
1397
1457
|
# 记一行,而那要等第一个页面建起来才看得见 —— 排障的人得在装载阶段就知道。
|
|
1398
1458
|
report["websocketGuard"] = _websocket_guard_capability()
|
|
@@ -1404,18 +1464,24 @@ def capabilities() -> dict[str, Any]:
|
|
|
1404
1464
|
|
|
1405
1465
|
def _wrap_extraction(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1406
1466
|
"""把 extraction 的 ValueError 归成协议里的 BAD_ARGS。"""
|
|
1467
|
+
raise_if_cancelled()
|
|
1407
1468
|
try:
|
|
1408
|
-
|
|
1469
|
+
result = fn(args)
|
|
1409
1470
|
except ValueError as error:
|
|
1410
1471
|
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1472
|
+
raise_if_cancelled()
|
|
1473
|
+
return result
|
|
1411
1474
|
|
|
1412
1475
|
|
|
1413
1476
|
def _wrap_search(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1414
1477
|
"""把 SearchError 的码原样转成协议错误。"""
|
|
1478
|
+
raise_if_cancelled()
|
|
1415
1479
|
try:
|
|
1416
|
-
|
|
1480
|
+
result = fn(args)
|
|
1417
1481
|
except search.SearchError as error:
|
|
1418
1482
|
raise AdapterError(error.code, str(error)) from error
|
|
1483
|
+
raise_if_cancelled()
|
|
1484
|
+
return result
|
|
1419
1485
|
|
|
1420
1486
|
|
|
1421
1487
|
def search_discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
@@ -1432,6 +1498,7 @@ METHODS = {
|
|
|
1432
1498
|
"select": select,
|
|
1433
1499
|
"locate": lambda args: _wrap_extraction(extraction.locate, args),
|
|
1434
1500
|
"links": lambda args: _wrap_extraction(extraction.links, args),
|
|
1501
|
+
"document.read": lambda args: document.read(args),
|
|
1435
1502
|
"search.discover": search_discover,
|
|
1436
1503
|
}
|
|
1437
1504
|
|
|
@@ -1443,24 +1510,26 @@ METHODS = {
|
|
|
1443
1510
|
# 会话把这份状态留在 sidecar 进程里跨请求复用 —— 这是 Scrapling 相对
|
|
1444
1511
|
# 「每次调用都重新来」最实用的一块。
|
|
1445
1512
|
#
|
|
1446
|
-
#
|
|
1513
|
+
# 三种类型与 Scrapling 的一一对应:
|
|
1447
1514
|
# static -> FetcherSession(curl_cffi)
|
|
1448
|
-
# stealth -> StealthySession(patchright
|
|
1515
|
+
# stealth -> StealthySession(patchright,本机启动浏览器)
|
|
1516
|
+
# remote -> RemoteSession(patchright,连接部署指定的 CDP 浏览器)
|
|
1449
1517
|
# ---------------------------------------------------------------------------
|
|
1450
1518
|
|
|
1451
1519
|
_SESSION_CLASSES = {
|
|
1452
1520
|
"static": "FetcherSession",
|
|
1453
1521
|
"stealth": "StealthySession",
|
|
1522
|
+
"remote": "RemoteSession",
|
|
1454
1523
|
}
|
|
1455
1524
|
|
|
1456
|
-
#
|
|
1457
|
-
_BROWSER_KINDS = frozenset({"stealth"})
|
|
1525
|
+
# 浏览器类会话:名额与专属执行线程都按它判。remote 不启动本机进程,但仍占用 page pool。
|
|
1526
|
+
_BROWSER_KINDS = frozenset({"stealth", "remote"})
|
|
1458
1527
|
|
|
1459
1528
|
# 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
|
|
1460
1529
|
# 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>, "lock": Lock,
|
|
1461
1530
|
# "worker": _SessionWorker | None};正在构造中的条目只有
|
|
1462
1531
|
# {"pending": True, "type": <str>, "lock": Lock},那样它就已经占了名额。
|
|
1463
|
-
# lock 从占位那一刻就存在,所以构造期与使用期是同一把锁;worker 只在
|
|
1532
|
+
# lock 从占位那一刻就存在,所以构造期与使用期是同一把锁;worker 只在 stealth/remote
|
|
1464
1533
|
# 上出现(见下),static 为 None。
|
|
1465
1534
|
_SESSIONS: dict[str, dict[str, Any]] = {}
|
|
1466
1535
|
|
|
@@ -1490,7 +1559,7 @@ class _SessionWorker:
|
|
|
1490
1559
|
``greenlet.error: cannot switch to a different thread``。而 bridge 的 worker 是
|
|
1491
1560
|
「谁抢到帧谁处理」,还会空闲 50ms 就退出换新线程:会话在 A 线程里开、下一个请求
|
|
1492
1561
|
几乎必然落在 B 线程。按会话加锁只能保证「不同时用」,保证不了「同一线程用」——
|
|
1493
|
-
所以每个
|
|
1562
|
+
所以每个 stealth/remote 会话配一条专用线程,open/fetch/close 全部投递到它,
|
|
1494
1563
|
串行执行;调用线程原地等结果。static(curl_cffi)没有线程亲和,不走这套。
|
|
1495
1564
|
"""
|
|
1496
1565
|
|
|
@@ -1519,10 +1588,11 @@ class _SessionWorker:
|
|
|
1519
1588
|
except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
|
|
1520
1589
|
done.set_exception(error)
|
|
1521
1590
|
|
|
1522
|
-
def run(self, fn: Callable[[], Any]) -> Any: # 会话调用的返回形态由引擎定
|
|
1591
|
+
def run(self, fn: Callable[[], Any], *, cancellable: bool = True) -> Any: # 会话调用的返回形态由引擎定
|
|
1523
1592
|
"""把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
|
|
1524
1593
|
|
|
1525
1594
|
:param fn: 要在属主线程上执行的调用
|
|
1595
|
+
:param cancellable: 请求任务在真实操作前复查取消;关闭会话等清理任务传 False
|
|
1526
1596
|
:returns: fn 的返回值
|
|
1527
1597
|
:raises AdapterError: 这条线程已经停止,投进去也没有人会执行
|
|
1528
1598
|
:raises BaseException: fn 抛什么这里就抛什么
|
|
@@ -1532,7 +1602,18 @@ class _SessionWorker:
|
|
|
1532
1602
|
if self._closed.is_set():
|
|
1533
1603
|
raise AdapterError("NO_SUCH_SESSION", "session has already been closed")
|
|
1534
1604
|
done: concurrent.futures.Future[Any] = concurrent.futures.Future()
|
|
1535
|
-
|
|
1605
|
+
# 新线程不会自动继承调用线程的 contextvar;每笔任务复制当前请求上下文,
|
|
1606
|
+
# 否则会话抓取/动作在属主线程上看不到 bridge 绑定的取消 token。
|
|
1607
|
+
context = contextvars.copy_context()
|
|
1608
|
+
|
|
1609
|
+
def invoke() -> Any:
|
|
1610
|
+
# 入队前取消只是第一道检查;任务可能在队列里等很久,必须出队后、真实操作前
|
|
1611
|
+
# 再查一次。清理任务显式豁免,否则取消中的 close 会把自己跳过并漏掉浏览器。
|
|
1612
|
+
if cancellable:
|
|
1613
|
+
raise_if_cancelled()
|
|
1614
|
+
return fn()
|
|
1615
|
+
|
|
1616
|
+
self._jobs.put((lambda: context.run(invoke), done))
|
|
1536
1617
|
try:
|
|
1537
1618
|
return done.result(timeout=_WORKER_RESULT_TIMEOUT_SECONDS)
|
|
1538
1619
|
except concurrent.futures.TimeoutError:
|
|
@@ -1559,6 +1640,19 @@ def _new_session_id() -> str:
|
|
|
1559
1640
|
return uuid.uuid4().hex[:12]
|
|
1560
1641
|
|
|
1561
1642
|
|
|
1643
|
+
def _remote_cdp_url(args: dict[str, Any]) -> str:
|
|
1644
|
+
"""读取部署级 CDP 端点;缺失或协议不符时在连接前报参数错误。"""
|
|
1645
|
+
deployment = args.get("deployment")
|
|
1646
|
+
raw = deployment.get("browserCdpUrl") if isinstance(deployment, dict) else None
|
|
1647
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
1648
|
+
raise AdapterError("BAD_ARGS", "remote sessions require deployment.browserCdpUrl")
|
|
1649
|
+
endpoint = raw.strip()
|
|
1650
|
+
parsed = urlparse(endpoint)
|
|
1651
|
+
if parsed.scheme not in {"ws", "wss", "http", "https"} or not parsed.netloc:
|
|
1652
|
+
raise AdapterError("BAD_ARGS", "browserCdpUrl must be a ws/wss/http/https URL with a host")
|
|
1653
|
+
return endpoint
|
|
1654
|
+
|
|
1655
|
+
|
|
1562
1656
|
def _make_session(kind: str, args: dict[str, Any]) -> Any:
|
|
1563
1657
|
"""按类型造一个**已启动**的会话对象。
|
|
1564
1658
|
|
|
@@ -1567,7 +1661,7 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
|
|
|
1567
1661
|
cookie 与登录态 —— 那是会话存在的理由。绕过清单因此对浏览器会话不逐 URL 生效(对
|
|
1568
1662
|
静态会话生效,那边是每次请求各自的参数,换代理不丢任何东西)。
|
|
1569
1663
|
|
|
1570
|
-
:param kind: static /
|
|
1664
|
+
:param kind: static / stealth / remote
|
|
1571
1665
|
:param args: 创建参数
|
|
1572
1666
|
:returns: 已 start(或已进入上下文)的会话对象
|
|
1573
1667
|
:raises AdapterError: 类型不认识,或构造/启动失败
|
|
@@ -1588,8 +1682,6 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
|
|
|
1588
1682
|
# wrapper 要留在登记条目里,close 时才能 __exit__。
|
|
1589
1683
|
return logic, wrapper
|
|
1590
1684
|
|
|
1591
|
-
from scrapling.fetchers import StealthySession
|
|
1592
|
-
|
|
1593
1685
|
# 只有开场才生效的那些设置(block_ads / record_requests / headless / locale /
|
|
1594
1686
|
# timezone_id / useragent / executable_path / timeout)必须在这里进会话:
|
|
1595
1687
|
# fetch 层传过去会被 validate_fetch 静默丢掉(见 FETCH_LEVEL_KEYS)。
|
|
@@ -1613,7 +1705,21 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
|
|
|
1613
1705
|
# 是直连的:模型明确填了 blockWebrtc=false 也会被静默盖掉。
|
|
1614
1706
|
# 这里整体重写,不继承那份结论。
|
|
1615
1707
|
common["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
|
|
1616
|
-
session
|
|
1708
|
+
session: Any
|
|
1709
|
+
if kind == "remote":
|
|
1710
|
+
from scrapling.fetchers import RemoteSession
|
|
1711
|
+
|
|
1712
|
+
endpoint = _remote_cdp_url(args)
|
|
1713
|
+
# RemoteSession 只接受 context 级参数;real_chrome 会被上游明确拒绝,
|
|
1714
|
+
# executable_path 与 headless 则只对本机启动有意义。
|
|
1715
|
+
common.pop("real_chrome", None)
|
|
1716
|
+
common.pop("executable_path", None)
|
|
1717
|
+
common.pop("headless", None)
|
|
1718
|
+
session = RemoteSession(cdp_url=endpoint, new_context=True, **common)
|
|
1719
|
+
else:
|
|
1720
|
+
from scrapling.fetchers import StealthySession
|
|
1721
|
+
|
|
1722
|
+
session = StealthySession(**common)
|
|
1617
1723
|
session.start()
|
|
1618
1724
|
return session, session
|
|
1619
1725
|
|
|
@@ -1670,7 +1776,7 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1670
1776
|
_SESSIONS[session_id] = placeholder
|
|
1671
1777
|
entry_lock = placeholder["lock"]
|
|
1672
1778
|
|
|
1673
|
-
#
|
|
1779
|
+
# stealth/remote 先起属主线程,构造(含 sync_playwright 的启动)整个发生在它上面
|
|
1674
1780
|
# —— greenlet 绑定从此指向这条线程,之后每次 fetch/close 都转交回来。static 没有
|
|
1675
1781
|
# 线程亲和,留在调用线程即可。
|
|
1676
1782
|
worker: _SessionWorker | None = None
|
|
@@ -1680,6 +1786,13 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1680
1786
|
else:
|
|
1681
1787
|
worker = _SessionWorker()
|
|
1682
1788
|
usable, closer = worker.run(lambda: _make_session(kind, args))
|
|
1789
|
+
except RequestCancelled:
|
|
1790
|
+
if worker is not None:
|
|
1791
|
+
worker.stop()
|
|
1792
|
+
with _SESSION_LOCK:
|
|
1793
|
+
if _SESSIONS.get(session_id) is placeholder:
|
|
1794
|
+
_SESSIONS.pop(session_id, None)
|
|
1795
|
+
raise
|
|
1683
1796
|
except BaseException as error:
|
|
1684
1797
|
if worker is not None:
|
|
1685
1798
|
worker.stop()
|
|
@@ -1689,6 +1802,23 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1689
1802
|
raise
|
|
1690
1803
|
raise AdapterError("SESSION_OPEN_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1691
1804
|
|
|
1805
|
+
try:
|
|
1806
|
+
# 构造可能耗时数百毫秒;返回后先复查,取消时刚建好的浏览器必须先关掉,绝不能
|
|
1807
|
+
# 插进注册表等一个永远不会到来的请求。清理任务在属主线程执行且不受取消影响。
|
|
1808
|
+
raise_if_cancelled()
|
|
1809
|
+
except RequestCancelled:
|
|
1810
|
+
abandoned_entry = {"closer": closer, "type": kind, "lock": entry_lock}
|
|
1811
|
+
if worker is not None:
|
|
1812
|
+
with contextlib.suppress(Exception):
|
|
1813
|
+
worker.run(lambda: _release_entry(abandoned_entry), cancellable=False)
|
|
1814
|
+
worker.stop()
|
|
1815
|
+
else:
|
|
1816
|
+
_release_entry(abandoned_entry)
|
|
1817
|
+
with _SESSION_LOCK:
|
|
1818
|
+
if _SESSIONS.get(session_id) is placeholder:
|
|
1819
|
+
_SESSIONS.pop(session_id, None)
|
|
1820
|
+
raise
|
|
1821
|
+
|
|
1692
1822
|
with _SESSION_LOCK:
|
|
1693
1823
|
abandoned = placeholder.get("closed_while_pending") is True
|
|
1694
1824
|
if abandoned:
|
|
@@ -1704,7 +1834,7 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1704
1834
|
"settings": _session_settings(kind, args),
|
|
1705
1835
|
# 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
|
|
1706
1836
|
"lock": entry_lock,
|
|
1707
|
-
#
|
|
1837
|
+
# stealth/remote 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
|
|
1708
1838
|
"worker": worker,
|
|
1709
1839
|
}
|
|
1710
1840
|
created_at = _SESSIONS[session_id]["created_at"]
|
|
@@ -1716,7 +1846,7 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1716
1846
|
# 浏览器会话的 close 必须在属主线程上跑:Playwright 的同步 API 与创建它的线程
|
|
1717
1847
|
# 绑定,跨线程调用抛 greenlet 错误,而 _release_entry 会 suppress 掉它 ——
|
|
1718
1848
|
# 随后 stop() 又把属主线程收掉,这个 Chromium 就再没有任何线程能关。
|
|
1719
|
-
worker.run(lambda: _release_entry(abandoned_entry))
|
|
1849
|
+
worker.run(lambda: _release_entry(abandoned_entry), cancellable=False)
|
|
1720
1850
|
worker.stop()
|
|
1721
1851
|
else:
|
|
1722
1852
|
_release_entry(abandoned_entry)
|
|
@@ -1768,6 +1898,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1768
1898
|
# 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
|
|
1769
1899
|
# 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个会话」。表现是看不懂
|
|
1770
1900
|
# 的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
|
|
1901
|
+
raise_if_cancelled()
|
|
1771
1902
|
try:
|
|
1772
1903
|
if entry["type"] == "static":
|
|
1773
1904
|
with entry["lock"]:
|
|
@@ -1775,6 +1906,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1775
1906
|
# 会持锁使用一份已关闭的会话,异常最终被归成 FETCH_FAILED——语义错位。
|
|
1776
1907
|
if entry.get("closed") is True:
|
|
1777
1908
|
raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
|
|
1909
|
+
raise_if_cancelled()
|
|
1778
1910
|
# 与一次性 fetch 同一条复判:static 会话的请求不经过浏览器的 page.route,
|
|
1779
1911
|
# 少了这一道,「Host 判完 → curl_cffi 自己再解析」之间就是敞开的。
|
|
1780
1912
|
allowed, reason = guard.url_allowed(url)
|
|
@@ -1841,7 +1973,10 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1841
1973
|
worker: _SessionWorker | None = entry["worker"]
|
|
1842
1974
|
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1843
1975
|
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1976
|
+
raise_if_cancelled()
|
|
1844
1977
|
response = worker.run(lambda: session.fetch(url, **params))
|
|
1978
|
+
except RequestCancelled:
|
|
1979
|
+
raise
|
|
1845
1980
|
except AdapterError:
|
|
1846
1981
|
raise
|
|
1847
1982
|
except Exception as error:
|
|
@@ -1866,6 +2001,9 @@ def session_read(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1866
2001
|
if entry["type"] == "static":
|
|
1867
2002
|
raise AdapterError("BAD_ARGS", "only browser sessions keep a current page")
|
|
1868
2003
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
2004
|
+
snapshot_type = args.get("snapshotType", "text")
|
|
2005
|
+
if not isinstance(snapshot_type, str) or snapshot_type not in {"text", "aria"}:
|
|
2006
|
+
raise AdapterError("BAD_ARGS", "snapshotType must be text or aria")
|
|
1869
2007
|
worker: _SessionWorker | None = entry["worker"]
|
|
1870
2008
|
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1871
2009
|
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
@@ -1880,6 +2018,7 @@ def session_read(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1880
2018
|
max_content_chars=limit,
|
|
1881
2019
|
include_metadata=bool(args.get("includeMetadata", False)),
|
|
1882
2020
|
strip_inline_images=_strip_inline_images(args),
|
|
2021
|
+
snapshot_type=snapshot_type,
|
|
1883
2022
|
)
|
|
1884
2023
|
)
|
|
1885
2024
|
|
|
@@ -1919,6 +2058,11 @@ def download(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1919
2058
|
return media.download(args)
|
|
1920
2059
|
|
|
1921
2060
|
|
|
2061
|
+
def document_read(args: dict[str, Any]) -> dict[str, Any]:
|
|
2062
|
+
"""PDF 文本读取入口。"""
|
|
2063
|
+
return document.read(args)
|
|
2064
|
+
|
|
2065
|
+
|
|
1922
2066
|
def screenshot(args: dict[str, Any]) -> dict[str, Any]:
|
|
1923
2067
|
"""截当前会话页;不会新建浏览器。"""
|
|
1924
2068
|
entry = _get_session(args.get("sessionId"))
|
|
@@ -2080,7 +2224,7 @@ def _close_entry(session_id: Any) -> None:
|
|
|
2080
2224
|
# 浏览器会话的 close 是一次 Playwright 远端调用,必须在属主线程上做;转交进去
|
|
2081
2225
|
# 还天然排在在途 fetch 之后 —— 「抓取进行中收到 close」会等抓取落地再关,而
|
|
2082
2226
|
# 不是把一次正在跑的抓取从底下抽走。
|
|
2083
|
-
worker.run(lambda: _release_entry(entry))
|
|
2227
|
+
worker.run(lambda: _release_entry(entry), cancellable=False)
|
|
2084
2228
|
worker.stop()
|
|
2085
2229
|
return
|
|
2086
2230
|
# static 没有属主线程,用 entry 锁:否则「抓取进行中收到 close」会把一次正在跑的
|
|
@@ -2130,8 +2274,8 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
2130
2274
|
worker: _SessionWorker | None = entry["worker"]
|
|
2131
2275
|
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
2132
2276
|
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
2133
|
-
matches = worker.run(lambda:
|
|
2134
|
-
return {"sessionId": session_id, "count":
|
|
2277
|
+
matches, count = worker.run(lambda: _network_summary_with_count(recorder, query=query))
|
|
2278
|
+
return {"sessionId": session_id, "count": count, "matches": matches}
|
|
2135
2279
|
|
|
2136
2280
|
|
|
2137
2281
|
def _state_path(args: dict[str, Any]) -> str:
|
|
@@ -2198,6 +2342,8 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
2198
2342
|
Path(target).chmod(0o600)
|
|
2199
2343
|
else:
|
|
2200
2344
|
worker.run(lambda: session.load_state(target))
|
|
2345
|
+
except RequestCancelled:
|
|
2346
|
+
raise
|
|
2201
2347
|
except FileNotFoundError as error:
|
|
2202
2348
|
if saving:
|
|
2203
2349
|
# save 路径的 FileNotFoundError 只能是目录在 mkdir 之后又不可用(竞态、权限):
|