@jayyuen66/dsh-scrapling 0.0.0-stage → 0.0.1-rc.1

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/py/adapters.py ADDED
@@ -0,0 +1,844 @@
1
+ """py/adapters.py —— Scrapling 各引擎的薄封装。
2
+
3
+ 只做三件事:把协议里的参数映射到 Scrapling 的调用、把 ``Response`` 归一成一份可
4
+ JSON 序列化的字典、把 Scrapling 的异常翻译成协议错误码。**不掺策略判断** —— URL 的
5
+ 安全判定由 Host 侧与 guard.py 各做一遍,这里只负责「按调度好的方式把请求打出去」。
6
+
7
+ 引擎对照(``scrapling/fetchers/``)::
8
+
9
+ Fetcher curl_cffi 静态抓取,只有 get/post/put/delete,没有 fetch()
10
+ DynamicFetcher Playwright Chromium
11
+ StealthyFetcher patchright Chromium
12
+
13
+ 三者的返回都是 ``Response``,而 ``Response`` 继承 ``Selector``,所以抓完可以直接
14
+ css/xpath。所有浏览器引擎都是**一次性 session**:每次调用开进程、结束即关。会话复用
15
+ 必须走 ``*Session`` 类(``scrapling.fetchers`` 导出),不能靠本模块复用。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import uuid
21
+ from datetime import datetime, timezone
22
+ from typing import Any
23
+
24
+ import guard
25
+
26
+ # Scrapling 缺失时不要让整个 sidecar 起不来:桥接层会把它报成能力缺失,
27
+ # 而不是让 Host 侧只看到一个「进程崩了」。
28
+ try: # pragma: no cover —— 取决于运行环境是否装了 scrapling
29
+ from scrapling.fetchers import DynamicFetcher, Fetcher, StealthyFetcher
30
+ except ImportError: # pragma: no cover
31
+ Fetcher = DynamicFetcher = StealthyFetcher = None # type: ignore[assignment]
32
+
33
+ SCRAPLING_AVAILABLE = Fetcher is not None
34
+
35
+ DEFAULT_EXTRACTION = "markdown"
36
+ DEFAULT_TIMEOUT_SECONDS = 120.0
37
+ DEFAULT_TIMEOUT_MS = 30_000
38
+ DEFAULT_MAX_CONTENT_CHARS = 200_000
39
+ EXTRACTION_TYPES = ("markdown", "html", "text")
40
+
41
+
42
+ class AdapterError(RuntimeError):
43
+ """带机器可读错误码的抓取失败。"""
44
+
45
+ def __init__(self, code: str, message: str) -> None:
46
+ super().__init__(message)
47
+ self.code = code
48
+
49
+
50
+ def _require(engine: object) -> None:
51
+ """引擎不可用时给出可执行的提示,而不是抛一个裸 AttributeError。"""
52
+ if engine is None:
53
+ raise AdapterError(
54
+ "SCRAPLING_MISSING",
55
+ 'Scrapling is not importable in this Python environment. '
56
+ 'Install it with: pip install "scrapling[rag]"',
57
+ )
58
+
59
+
60
+ def _positive_int(value: Any, field: str, default: int) -> int:
61
+ """取一个正整数;类型不对就报错,而不是静默用默认值。"""
62
+ if value is None:
63
+ return default
64
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
65
+ raise AdapterError("BAD_ARGS", f"{field} must be a positive integer")
66
+ return value
67
+
68
+
69
+ def _positive_number(value: Any, field: str, default: float) -> float:
70
+ """取一个正数。"""
71
+ if value is None:
72
+ return default
73
+ if not isinstance(value, (int, float)) or isinstance(value, bool) or value <= 0:
74
+ raise AdapterError("BAD_ARGS", f"{field} must be a positive number")
75
+ return float(value)
76
+
77
+
78
+ def _string_map(value: Any, field: str) -> dict[str, str] | None:
79
+ """把一个对象参数字典压成 ``dict[str, str]``;不是对象则报错。"""
80
+ if value is None:
81
+ return None
82
+ if not isinstance(value, dict):
83
+ raise AdapterError("BAD_ARGS", f"{field} must be an object or null")
84
+ return {str(key): str(item) for key, item in value.items()}
85
+
86
+
87
+ def clip(text: str, limit: int) -> tuple[str, bool]:
88
+ """按字符数截断,返回 (文本, 是否被截断)。
89
+
90
+ 截在代理对中间会产生孤立高代理,进会话日志后会让后续 Messages 请求整体失败,
91
+ 所以末尾的孤立高代理要丢掉。
92
+ """
93
+ if len(text) <= limit:
94
+ return text, False
95
+ cut = text[:limit]
96
+ if 0xD800 <= ord(cut[-1]) <= 0xDBFF:
97
+ cut = cut[:-1]
98
+ return cut, True
99
+
100
+
101
+ def _jsonable(value: Any) -> Any:
102
+ """把 Scrapling 返回的对象归一成可 JSON 序列化的结构。"""
103
+ if isinstance(value, (str, int, float, bool)) or value is None:
104
+ return value
105
+ if isinstance(value, dict):
106
+ return {str(key): _jsonable(item) for key, item in value.items()}
107
+ if isinstance(value, (list, tuple)):
108
+ return [_jsonable(item) for item in value]
109
+ return str(value)
110
+
111
+
112
+ def _xhr_summary(responses: Any) -> list[dict[str, Any]]:
113
+ """把 ``captured_xhr`` 压成轻量摘要。
114
+
115
+ XHR 响应体可能很大,全量塞回 Host 会把模型上下文撑爆;这里只给 URL、状态码与
116
+ 字节数,模型自己决定要不要再对其中某个 URL 发一次抓取。
117
+ """
118
+ summary: list[dict[str, Any]] = []
119
+ for item in responses or ():
120
+ try:
121
+ summary.append({"url": item.url, "status": item.status, "bytes": len(item.body)})
122
+ except Exception: # noqa: BLE001 —— 单条摘要失败不该拖垮整次抓取
123
+ continue
124
+ return summary
125
+
126
+
127
+ def _extraction(args: dict[str, Any]) -> tuple[str, str | None, bool, int]:
128
+ """抽出四个抽取相关参数并校验。
129
+
130
+ :param args: 协议参数
131
+ :returns: (extraction_type, css_selector, main_content_only, max_content_chars)
132
+ """
133
+ extraction_type = str(args.get("extractionType", DEFAULT_EXTRACTION))
134
+ if extraction_type not in EXTRACTION_TYPES:
135
+ raise AdapterError("BAD_ARGS", f"unknown extractionType: {extraction_type}")
136
+ css_selector = args.get("cssSelector")
137
+ if css_selector is not None and not isinstance(css_selector, str):
138
+ raise AdapterError("BAD_ARGS", "cssSelector must be a string or null")
139
+ return (
140
+ extraction_type,
141
+ css_selector,
142
+ bool(args.get("mainContentOnly", True)),
143
+ _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS),
144
+ )
145
+
146
+
147
+ def _sanitized_page(response: Any, *, main_content_only: bool) -> Any:
148
+ """按 ``Response.markdown()`` 的口径拿到清洗过的树。
149
+
150
+ markdown 那条路径走的是 ``Convertor._sanitize_for_ai(Convertor._strip_noise_tags(page))``,
151
+ 与 ``main_content_only`` 无关、无条件执行。直接取 ``response.html_content`` /
152
+ ``get_all_text`` 就绕开了它,于是 script、display:none、aria-hidden、template、
153
+ noscript 的内容会原样进模型上下文。这里对齐 markdown 的口径,顺带让 main_content_only
154
+ 对三条路径含义一致。
155
+ """
156
+ from scrapling.core.shell import Convertor
157
+
158
+ page = (response.css("body").first or response) if main_content_only else response
159
+ return Convertor._sanitize_for_ai(Convertor._strip_noise_tags(page))
160
+
161
+
162
+ def _strip_active_content(page: Any) -> None:
163
+ """剥掉元素上的可执行残留,让清洗后的 HTML 真的只剩内容。
164
+
165
+ ``_strip_noise_tags`` / ``_sanitize_for_ai`` 只处理元素与文本,**不碰属性**。实测
166
+ 清洗后 ``onclick`` 照样在,``<meta http-equiv=refresh>`` 与 ``srcdoc`` 也照样在 ——
167
+ 那些是事件处理器与跳转指令,直接把内网地址带进模型上下文。html 那条路径还回传
168
+ 完整标签,所以得在这里补一刀;text 路径取的是文本,不受属性影响。
169
+ """
170
+ root = getattr(page, "_root", None)
171
+ if root is None or not hasattr(root, "iter"):
172
+ return
173
+ for element in list(root.iter()):
174
+ tag = str(getattr(element, "tag", "") or "").lower()
175
+ # lxml 的 attrib 是 _Attrib,不是 dict 子类 —— 这里只能鸭子类型判断。
176
+ attrib = getattr(element, "attrib", None)
177
+ if attrib is None or not hasattr(attrib, "keys"):
178
+ continue
179
+ # meta refresh 能把浏览器导航到内网地址;base 同样只影响解析、不贡献内容。
180
+ if tag in ("meta", "base") and "http-equiv" in attrib:
181
+ attrib.clear()
182
+ continue
183
+ for name in [
184
+ key
185
+ for key in list(attrib.keys())
186
+ if key.lower().startswith("on") or key.lower() in ("srcdoc", "formaction")
187
+ ]:
188
+ del attrib[name]
189
+
190
+
191
+ def to_payload(
192
+ response: Any,
193
+ *,
194
+ extraction_type: str,
195
+ css_selector: str | None,
196
+ main_content_only: bool,
197
+ max_content_chars: int,
198
+ ) -> dict[str, Any]:
199
+ """把 Scrapling 的 ``Response`` 归一成协议载荷。
200
+
201
+ 反注入清洗对三条提取路径都无条件发生(``Convertor._strip_noise_tags`` +
202
+ ``_sanitize_for_ai``)—— 这里**不提供关闭它的开关**。官方 MCP server 在
203
+ ``main_content_only=False`` 时会绕过清洗,本插件不重复这个错。
204
+ """
205
+ if extraction_type == "html":
206
+ page = _sanitized_page(response, main_content_only=main_content_only)
207
+ _strip_active_content(page)
208
+ content = page.html_content
209
+ elif extraction_type == "text":
210
+ page = _sanitized_page(response, main_content_only=main_content_only)
211
+ content = page.get_all_text(
212
+ strip=True,
213
+ ignore_tags=("script", "style", "noscript", "svg", "iframe"),
214
+ )
215
+ else:
216
+ content = response.markdown(css_selector=css_selector, main_content_only=main_content_only)
217
+
218
+ clipped, truncated = clip(str(content), max_content_chars)
219
+ payload: dict[str, Any] = {
220
+ "url": response.url,
221
+ "status": response.status,
222
+ "extractionType": extraction_type,
223
+ "content": clipped,
224
+ "truncated": truncated,
225
+ "redirects": len(getattr(response, "history", ()) or ()),
226
+ }
227
+ captured = _xhr_summary(getattr(response, "captured_xhr", None))
228
+ if captured:
229
+ payload["xhr"] = captured
230
+ return payload
231
+
232
+
233
+ def _static_params(args: dict[str, Any], url: str) -> dict[str, Any]:
234
+ """静态抓取的公共参数。
235
+
236
+ ``follow_redirects="safe"`` 是关键:curl_cffi 会拒绝跳向私网的重定向,
237
+ 这是 Host 侧预校验之外的第二道防线(两者之间仍有 TOCTOU 窗口,见 README)。
238
+
239
+ ``proxies`` 只在用户配了代理或绕过清单时才出现(guard 那边返回 None 表示
240
+ 「本包不表态」),那时由本包决定走哪个出口;否则一个字都不传,让 curl_cffi
241
+ 按自己的 trust_env 读环境 —— 与本包不介入时逐字节一致。
242
+ """
243
+ params: dict[str, Any] = {
244
+ "timeout": _positive_number(
245
+ args.get("timeoutSeconds"), "timeoutSeconds", DEFAULT_TIMEOUT_SECONDS
246
+ ),
247
+ "follow_redirects": "safe",
248
+ "retries": _positive_int(args.get("retries"), "retries", 3),
249
+ }
250
+ proxies = guard.proxies_for(url)
251
+ if proxies is not None:
252
+ params["proxies"] = proxies
253
+ headers = _string_map(args.get("headers"), "headers")
254
+ if headers is not None:
255
+ params["headers"] = headers
256
+ return params
257
+
258
+
259
+ def _url(args: dict[str, Any]) -> str:
260
+ """取必填的 url 参数。"""
261
+ url = args.get("url")
262
+ if not isinstance(url, str) or not url:
263
+ raise AdapterError("BAD_ARGS", "url is required")
264
+ return url
265
+
266
+
267
+ def fetch(args: dict[str, Any]) -> dict[str, Any]:
268
+ """静态抓取(curl_cffi)。不需要浏览器。
269
+
270
+ :param args: 协议参数
271
+ :returns: 归一后的载荷
272
+ """
273
+ _require(Fetcher)
274
+ url = _url(args)
275
+ extraction_type, css_selector, main_content_only, limit = _extraction(args)
276
+ params = _static_params(args, url)
277
+
278
+ cookies = _string_map(args.get("cookies"), "cookies")
279
+ if cookies is not None:
280
+ params["cookies"] = cookies
281
+ impersonate = args.get("impersonate")
282
+ if isinstance(impersonate, str) and impersonate:
283
+ params["impersonate"] = impersonate
284
+
285
+ method = str(args.get("method", "GET")).upper()
286
+ if method not in ("GET", "POST", "PUT", "DELETE"):
287
+ raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
288
+ if method != "GET":
289
+ body = args.get("body")
290
+ if isinstance(body, dict):
291
+ params["json"] = _jsonable(body)
292
+ elif isinstance(body, str):
293
+ params["data"] = body
294
+
295
+ response = getattr(Fetcher, method.lower())(url, **params)
296
+ return to_payload(
297
+ response,
298
+ extraction_type=extraction_type,
299
+ css_selector=css_selector,
300
+ main_content_only=main_content_only,
301
+ max_content_chars=limit,
302
+ )
303
+
304
+
305
+ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
306
+ """浏览器抓取的公共参数。
307
+
308
+ ``block_ads`` 由部署设置决定,可以打开:它并不会与 SSRF 守卫抢 handler。
309
+ 上游把 ``block_ads`` 折进**同一个** ``blocked_domains``(engines/_browsers/
310
+ _validators.py),交给 engines/_browsers/_base.py 里那一个
311
+ ``create_intercept_handler``;而那个 handler 是在 ``page_setup`` **之前**注册的,
312
+ 守卫在 ``page_setup`` 里后注册、因而先跑。守卫放行时走 ``route.fallback()``
313
+ (不是 ``continue_()``),所以上游的拦截能叠加在守卫判定之上,SSRF 那一道不受影响。
314
+
315
+ ``blocked_domains`` / ``disable_resources`` 仍固定关闭:本包没有对应的部署设置,
316
+ 而打开它们同样只是给上游那个 handler 加料,不会削弱守卫。
317
+
318
+ 代理在这里显式交给引擎,是三条抓取路径里唯一必须这么做的一条:Chromium 不读
319
+ ``HTTP_PROXY``/``ALL_PROXY``,只读系统代理设置,于是一台只在 shell 里 export 过代理
320
+ 的机器上静态抓取走代理、浏览器抓取却直连。传 ``proxy`` 给 ``DynamicFetcher.fetch`` /
321
+ ``StealthyFetcher.fetch`` 时它落进**会话**配置(fetchers/*.py 里是
322
+ ``DynamicSession(**kwargs)``),进 ``launch_persistent_context`` 的 context 选项 ——
323
+ 所以是一次抓取一个 context,与一次性会话的既有形态一致,且不会丢 cookie。
324
+ """
325
+ params: dict[str, Any] = {
326
+ "headless": bool(args.get("headless", True)),
327
+ "timeout": _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS),
328
+ "block_ads": bool(args.get("blockAds", False)),
329
+ "blocked_domains": None,
330
+ "disable_resources": False,
331
+ }
332
+ proxy = guard.browser_proxy(url)
333
+ if proxy is not None:
334
+ params["proxy"] = proxy
335
+ # WebRTC 能绕过代理直接发 UDP,页面里一句 STUN 就能问出访客的真实出口 IP。
336
+ # 走代理时那条信息本就不该泄露,所以两套引擎都上对应的开关:patchright 有
337
+ # block_webrtc,Playwright 没有,只能用 Chromium 的启动 flag。
338
+ params["extra_flags"] = [guard.WEBRTC_NO_LEAK_FLAG]
339
+ if args.get("networkIdle"):
340
+ params["network_idle"] = True
341
+ for key, name in (
342
+ ("waitSelector", "wait_selector"),
343
+ ("waitSelectorState", "wait_selector_state"),
344
+ ("useragent", "useragent"),
345
+ ("locale", "locale"),
346
+ ("timezoneId", "timezone_id"),
347
+ ("captureXhrPattern", "capture_xhr"),
348
+ ):
349
+ value = args.get(key)
350
+ if isinstance(value, str) and value:
351
+ params[name] = value
352
+ # 浏览器二进制路径与 CDP 端点只从 deployment 命名空间取,不在上面的模型可见透传表里:
353
+ # executable_path 等于「让 Chromium 去执行这个文件」,cdp_url 等于「把浏览器交给这个
354
+ # 调试端点」,两者都是部署级的强能力,但绝不能由模型入参驱动。Host 侧对应的两枚设置
355
+ # 同样是非 volatile 的部署级字段(不进设置卡)。
356
+ deployment = args.get("deployment")
357
+ if isinstance(deployment, dict):
358
+ for source, target in (
359
+ ("browserExecutablePath", "executable_path"),
360
+ ("browserCdpUrl", "cdp_url"),
361
+ ):
362
+ value = deployment.get(source)
363
+ if isinstance(value, str) and value:
364
+ params[target] = value
365
+ wait_ms = args.get("waitMs")
366
+ if isinstance(wait_ms, (int, float)) and not isinstance(wait_ms, bool) and wait_ms > 0:
367
+ params["wait"] = wait_ms
368
+ extra_headers = _string_map(args.get("extraHeaders"), "extraHeaders")
369
+ if extra_headers is not None:
370
+ params["extra_headers"] = extra_headers
371
+ return params
372
+
373
+
374
+ def render(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
375
+ """浏览器抓取。``stealth`` 为真时走 patchright 引擎。
376
+
377
+ :param args: 协议参数
378
+ :param stealth: 是否用 StealthyFetcher
379
+ :returns: 归一后的载荷
380
+ """
381
+ engine = StealthyFetcher if stealth else DynamicFetcher
382
+ _require(engine)
383
+ url = _url(args)
384
+ extraction_type, css_selector, main_content_only, limit = _extraction(args)
385
+
386
+ params = _browser_params(args, url)
387
+ params["page_setup"] = page_setup
388
+ if stealth:
389
+ params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
390
+ params["hide_canvas"] = bool(args.get("hideCanvas", False))
391
+ # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
392
+ # 插件正是为了不泄露它。
393
+ params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or "proxy" in params
394
+ params["allow_webgl"] = bool(args.get("allowWebgl", True))
395
+
396
+ response = engine.fetch(url, **params)
397
+ return to_payload(
398
+ response,
399
+ extraction_type=extraction_type,
400
+ css_selector=css_selector,
401
+ main_content_only=main_content_only,
402
+ max_content_chars=limit,
403
+ )
404
+
405
+
406
+ def _fake_response(html: str, url: str, status: int) -> Any:
407
+ """造一个不带网络的 ``Response``,给离线抽取用。"""
408
+ from scrapling.engines.toolbelt.custom import Response
409
+
410
+ return Response(
411
+ url=url,
412
+ content=html,
413
+ status=status,
414
+ reason="",
415
+ cookies={},
416
+ headers={},
417
+ request_headers={},
418
+ )
419
+
420
+
421
+ def extract(args: dict[str, Any]) -> dict[str, Any]:
422
+ """对一段已有 HTML 做抽取,不发任何网络请求。
423
+
424
+ :param args: 协议参数
425
+ :returns: 归一后的载荷
426
+ """
427
+ html = args.get("html")
428
+ if not isinstance(html, str):
429
+ raise AdapterError("BAD_ARGS", "html must be a string")
430
+ extraction_type, css_selector, main_content_only, limit = _extraction(args)
431
+ status = args.get("status", 200)
432
+ if not isinstance(status, int) or isinstance(status, bool):
433
+ raise AdapterError("BAD_ARGS", "status must be an integer")
434
+ response = _fake_response(html, str(args.get("url") or "about:blank"), status)
435
+ return to_payload(
436
+ response,
437
+ extraction_type=extraction_type,
438
+ css_selector=css_selector,
439
+ main_content_only=main_content_only,
440
+ max_content_chars=limit,
441
+ )
442
+
443
+
444
+ def select(args: dict[str, Any]) -> dict[str, Any]:
445
+ """对已有 HTML 做 CSS/XPath 选择,返回命中的文本与少量属性。
446
+
447
+ 这正是 dsh 内置 ``web_fetch`` 结构上做不到的那部分:它只能给一整块 Markdown,
448
+ 这里给的是选择器命中的具体内容。
449
+ """
450
+ from scrapling.parser import Selector
451
+
452
+ html = args.get("html")
453
+ if not isinstance(html, str):
454
+ raise AdapterError("BAD_ARGS", "html must be a string")
455
+ selector = args.get("selector")
456
+ if not isinstance(selector, str) or not selector:
457
+ raise AdapterError("BAD_ARGS", "selector is required")
458
+ attribute = args.get("attribute")
459
+ if attribute is not None and not isinstance(attribute, str):
460
+ raise AdapterError("BAD_ARGS", "attribute must be a string or null")
461
+
462
+ page = Selector(html)
463
+ nodes = page.xpath(selector) if bool(args.get("useXpath", False)) else page.css(selector)
464
+ limit = _positive_int(args.get("limit"), "limit", 200)
465
+ include_attributes = bool(args.get("includeAttributes", False))
466
+
467
+ matches: list[dict[str, Any]] = []
468
+ for node in nodes[:limit]:
469
+ item: dict[str, Any] = {"tag": node.tag}
470
+ if attribute:
471
+ item["value"] = str(node.attrib.get(attribute, ""))
472
+ else:
473
+ item["text"] = str(node.get_all_text(strip=True))
474
+ if include_attributes:
475
+ item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
476
+ matches.append(item)
477
+ return {
478
+ "count": len(nodes),
479
+ "truncated": len(nodes) > len(matches),
480
+ "matches": _jsonable(matches),
481
+ }
482
+
483
+
484
+ def page_setup(page: object) -> None:
485
+ """Scrapling ``page_setup`` 回调:装上网络守卫。
486
+
487
+ 绝不能把这个回调本身暴露成模型可传的参数 —— 那等于给被 prompt 注入的模型一个
488
+ 任意代码执行入口。Scrapling 官方 MCP 的 ``_EXCLUDED_FETCH_KEYS`` 是同一个道理。
489
+ """
490
+ from guard import install
491
+
492
+ install(page)
493
+
494
+
495
+ def _scrapling_version() -> str:
496
+ """读 Scrapling 版本号;读不到给空串,不让能力探测整体失败。"""
497
+ try:
498
+ import scrapling
499
+
500
+ return str(scrapling.__version__)
501
+ except Exception: # noqa: BLE001
502
+ return ""
503
+
504
+
505
+ def _probe_browser(module_name: str) -> bool:
506
+ """起一次浏览器再关掉,确认浏览器二进制真的可用。
507
+
508
+ 为什么直接用 Playwright/patchright 而不走 ``engine.fetch``:Scrapling 的 fetch 会在
509
+ ``page.goto`` 返回 None 时抛 "Failed to get response",而 ``data:`` 与 ``about:blank``
510
+ 这类 URL 恰好不产生 response。拿它们当探针 URL 会稳定地假失败,还会被 ``retries``
511
+ 放大成几秒钟的重试风暴。
512
+
513
+ 要验的其实只有一件事:**浏览器二进制装没装**。``playwright install chromium`` 与
514
+ patchright 各自管理浏览器,少任一个都会在真正调用时才炸,所以两个引擎都要单独探。
515
+
516
+ :param module_name - ``"playwright.sync_api"`` 或 ``"patchright.sync_api"``
517
+ :returns: 浏览器能否启动
518
+ """
519
+ import importlib
520
+
521
+ try:
522
+ sync_playwright = importlib.import_module(module_name).sync_playwright
523
+ with sync_playwright() as driver:
524
+ browser = driver.chromium.launch(headless=True)
525
+ browser.close()
526
+ except Exception: # noqa: BLE001 —— 探针只关心起没起得来,细节由 Host 侧提示用户
527
+ return False
528
+ return True
529
+
530
+
531
+ def capabilities() -> dict[str, Any]:
532
+ """报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
533
+ report: dict[str, Any] = {
534
+ "scrapling": SCRAPLING_AVAILABLE,
535
+ "static": SCRAPLING_AVAILABLE,
536
+ "extract": SCRAPLING_AVAILABLE,
537
+ "browser": False,
538
+ "stealth": False,
539
+ }
540
+ if not SCRAPLING_AVAILABLE:
541
+ return report
542
+ report["version"] = _scrapling_version()
543
+ report["browser"] = _probe_browser("playwright.sync_api")
544
+ report["stealth"] = _probe_browser("patchright.sync_api")
545
+ # 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
546
+ # server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
547
+ report["proxy"] = guard.proxy_settings()
548
+ return report
549
+
550
+
551
+ METHODS = {
552
+ "ping": lambda _args: {"pong": True},
553
+ "capabilities": lambda _args: capabilities(),
554
+ "fetch": fetch,
555
+ "render": lambda args: render(args, stealth=False),
556
+ "stealth_fetch": lambda args: render(args, stealth=True),
557
+ "extract": extract,
558
+ "select": select,
559
+ }
560
+
561
+
562
+ # ---------------------------------------------------------------------------
563
+ # 会话
564
+ #
565
+ # 一次性抓取每次都新开进程/新会话,cookie、登录态、浏览器实例全部丢失。
566
+ # 会话把这份状态留在 sidecar 进程里跨请求复用 —— 这是 Scrapling 相对
567
+ # 「每次调用都重新来」最实用的一块。
568
+ #
569
+ # 三种类型与 Scrapling 的一一对应:
570
+ # static -> FetcherSession(curl_cffi)
571
+ # browser -> DynamicSession(Playwright)
572
+ # stealth -> StealthySession(patchright)
573
+ # ---------------------------------------------------------------------------
574
+
575
+ _SESSION_CLASSES = {
576
+ "static": "FetcherSession",
577
+ "browser": "DynamicSession",
578
+ "stealth": "StealthySession",
579
+ }
580
+
581
+ # 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
582
+ # 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>}
583
+ _SESSIONS: dict[str, dict[str, Any]] = {}
584
+
585
+ # 同开几个会话。browser/stealth 每开一个就是一个真实的 Chromium 进程,而 sessionType 是
586
+ # **模型可选**的参数 —— 不设上限的话,「开 → 不关」重复几次就能把机器的内存吃光。
587
+ # 因此在登记之前就判,而不是指望模型记得调 session_close。
588
+ MAX_SESSIONS = 8
589
+ # 其中最多几个可以是吃内存的那两种。static 只是连接池,便宜得多。
590
+ MAX_BROWSER_SESSIONS = 3
591
+
592
+
593
+ def _new_session_id() -> str:
594
+ """生成一个短的会话 id。
595
+
596
+ :returns: 会话 id
597
+ """
598
+ return uuid.uuid4().hex[:12]
599
+
600
+
601
+ def _make_session(kind: str, args: dict[str, Any]) -> Any:
602
+ """按类型造一个**已启动**的会话对象。
603
+
604
+ 代理在浏览器会话上是**开的时候定一次**而不是每次 fetch 定:Playwright 的代理挂在
605
+ BrowserContext 上,中途换代理只能新建 context,而新建就等于丢掉这个会话攒下来的
606
+ cookie 与登录态 —— 那是会话存在的理由。绕过清单因此对浏览器会话不逐 URL 生效(对
607
+ 静态会话生效,那边是每次请求各自的参数,换代理不丢任何东西)。
608
+
609
+ :param kind: static / browser / stealth
610
+ :param args: 创建参数
611
+ :returns: 已 start(或已进入上下文)的会话对象
612
+ :raises AdapterError: 类型不认识,或构造/启动失败
613
+ """
614
+ if kind not in _SESSION_CLASSES:
615
+ raise AdapterError("BAD_ARGS", f"unknown session type: {kind}")
616
+
617
+ if kind == "static":
618
+ from scrapling.fetchers import FetcherSession
619
+
620
+ wrapper = FetcherSession(
621
+ impersonate=args.get("impersonate") or "chrome",
622
+ timeout=args.get("timeoutSeconds", DEFAULT_TIMEOUT_SECONDS),
623
+ )
624
+ # FetcherSession 自己没有 get/post —— 那些方法在 __enter__ 返回的
625
+ # _SyncSessionLogic 上。存错对象的话,调用时会报 'no attribute get'。
626
+ logic = wrapper.__enter__()
627
+ # wrapper 要留在登记条目里,close 时才能 __exit__。
628
+ return logic, wrapper
629
+
630
+ from scrapling.fetchers import DynamicSession, StealthySession
631
+
632
+ headless = bool(args.get("headless", True))
633
+ timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
634
+ common: dict[str, Any] = {"headless": headless, "timeout": timeout_ms}
635
+ # 会话开的时候还不知道要访问哪个主机,所以按「配了代理就用代理」定档;显式填过
636
+ # proxyBypass 的主机在会话里也跟着走代理 —— 见上面的取舍说明。
637
+ proxy = guard.split_proxy(guard.default_proxy())
638
+ if proxy is not None:
639
+ common["proxy"] = proxy
640
+ common["extra_flags"] = [guard.WEBRTC_NO_LEAK_FLAG]
641
+ if kind == "browser":
642
+ session = DynamicSession(**common)
643
+ else:
644
+ session = StealthySession(
645
+ **common,
646
+ solve_cloudflare=bool(args.get("solveCloudflare", False)),
647
+ hide_canvas=bool(args.get("hideCanvas", False)),
648
+ block_webrtc=bool(args.get("blockWebrtc", False)) or proxy is not None,
649
+ allow_webgl=bool(args.get("allowWebgl", True)),
650
+ )
651
+ session.start()
652
+ return session, session
653
+
654
+
655
+ def _enforce_session_limits(kind: str) -> None:
656
+ """在开新会话之前判一下名额,超了就明确报错而不是让机器被吃光。
657
+
658
+ 判否而不是自动关掉最旧的那个:关一个模型还握着的会话,会让它的下一次请求莫名断掉,
659
+ 而「到上限了,请先 close 一个」是模型自己能纠正的。
660
+
661
+ :param kind: 即将开的会话类型
662
+ :raises AdapterError: 总数或浏览器类会话数已到上限
663
+ """
664
+ from adapters import AdapterError
665
+
666
+ if len(_SESSIONS) >= MAX_SESSIONS:
667
+ raise AdapterError(
668
+ "SESSION_LIMIT",
669
+ f"{len(_SESSIONS)} sessions are already open (limit {MAX_SESSIONS}); "
670
+ "close one with session.close before opening another",
671
+ )
672
+ if kind in ("browser", "stealth"):
673
+ browsers = sum(1 for entry in _SESSIONS.values() if entry["type"] in ("browser", "stealth"))
674
+ if browsers >= MAX_BROWSER_SESSIONS:
675
+ raise AdapterError(
676
+ "SESSION_LIMIT",
677
+ f"{browsers} browser sessions are already open "
678
+ f"(limit {MAX_BROWSER_SESSIONS}); close one before opening another",
679
+ )
680
+
681
+
682
+ def session_open(args: dict[str, Any]) -> dict[str, Any]:
683
+ """开一个会话并登记。
684
+
685
+ :param args: 协议参数
686
+ :returns: 会话信息
687
+ :raises AdapterError: 类型不认识 / id 重复 / 构造失败
688
+ """
689
+ kind = str(args.get("sessionType", "static"))
690
+ session_id = args.get("sessionId") or _new_session_id()
691
+ if not isinstance(session_id, str) or not session_id:
692
+ raise AdapterError("BAD_ARGS", "sessionId must be a string")
693
+ if session_id in _SESSIONS:
694
+ raise AdapterError("BAD_ARGS", f"session already exists: {session_id}")
695
+ _enforce_session_limits(kind)
696
+
697
+ try:
698
+ usable, closer = _make_session(kind, args)
699
+ except AdapterError:
700
+ raise
701
+ except Exception as error: # noqa: BLE001
702
+ raise AdapterError("SESSION_OPEN_FAILED", f"{type(error).__name__}: {error}") from error
703
+
704
+ _SESSIONS[session_id] = {
705
+ "session": usable, # 真正发请求的对象
706
+ "closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
707
+ "type": kind,
708
+ # 浏览器会话是否带着代理;stealth 的 block_webrtc 要在每次 fetch 时跟着它走。
709
+ "proxied": kind != "static" and guard.default_proxy() != "",
710
+ "created_at": datetime.now(timezone.utc).isoformat(),
711
+ }
712
+ return {
713
+ "sessionId": session_id,
714
+ "sessionType": kind,
715
+ "createdAt": _SESSIONS[session_id]["created_at"],
716
+ }
717
+
718
+
719
+ def _get_session(session_id: Any) -> dict[str, Any]:
720
+ """按 id 取已登记的会话。
721
+
722
+ :param session_id: 会话 id
723
+ :returns: 登记条目
724
+ :raises AdapterError: id 缺失或不存在
725
+ """
726
+ if not isinstance(session_id, str) or not session_id:
727
+ raise AdapterError("BAD_ARGS", "sessionId is required")
728
+ entry = _SESSIONS.get(session_id)
729
+ if entry is None:
730
+ raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
731
+ return entry
732
+
733
+
734
+ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
735
+ """用已开好的会话抓一个 URL。
736
+
737
+ :param args: 协议参数
738
+ :returns: 归一后的载荷
739
+ :raises AdapterError: 会话不存在 / 类型不支持 / 抓取失败
740
+ """
741
+ entry = _get_session(args.get("sessionId"))
742
+ session = entry["session"]
743
+ extraction_type, css_selector, main_content_only, limit = _extraction(args)
744
+ url = _url(args)
745
+
746
+ try:
747
+ if entry["type"] == "static":
748
+ response = session.get(url, **_static_params(args, url))
749
+ else:
750
+ # 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL 覆盖 ——
751
+ # 覆盖的做法是新建 context,cookie 与登录态会随之清空。
752
+ params = _browser_params(args, url)
753
+ params.pop("proxy", None)
754
+ params.pop("extra_flags", None)
755
+ params["page_setup"] = page_setup
756
+ if entry["type"] == "stealth":
757
+ params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
758
+ params["hide_canvas"] = bool(args.get("hideCanvas", False))
759
+ params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or bool(
760
+ entry["proxied"]
761
+ )
762
+ params["allow_webgl"] = bool(args.get("allowWebgl", True))
763
+ response = session.fetch(url, **params)
764
+ except AdapterError:
765
+ raise
766
+ except Exception as error: # noqa: BLE001
767
+ raise AdapterError("FETCH_FAILED", f"{type(error).__name__}: {error}") from error
768
+
769
+ payload = to_payload(
770
+ response,
771
+ extraction_type=extraction_type,
772
+ css_selector=css_selector,
773
+ main_content_only=main_content_only,
774
+ max_content_chars=limit,
775
+ )
776
+ payload["sessionId"] = args.get("sessionId")
777
+ return payload
778
+
779
+
780
+ def session_list(_args: dict[str, Any]) -> dict[str, Any]:
781
+ """列出当前所有会话(不含任何凭据)。
782
+
783
+ :param _args: 协议参数,本方法不用
784
+ :returns: 会话列表
785
+ """
786
+ return {
787
+ "sessions": [
788
+ {
789
+ "sessionId": session_id,
790
+ "sessionType": entry["type"],
791
+ "createdAt": entry["created_at"],
792
+ }
793
+ for session_id, entry in _SESSIONS.items()
794
+ ]
795
+ }
796
+
797
+
798
+ def _close_entry(session_id: str) -> None:
799
+ """关掉一个会话并从注册表移除。
800
+
801
+ :param session_id: 会话 id
802
+ """
803
+ entry = _SESSIONS.pop(session_id, None)
804
+ if entry is None:
805
+ return
806
+ try:
807
+ entry["closer"].close() if entry["type"] != "static" else entry["closer"].__exit__(None, None, None)
808
+ except Exception: # noqa: BLE001 —— 关不掉也不能让桥接层挂掉
809
+ pass
810
+
811
+
812
+ def session_close(args: dict[str, Any]) -> dict[str, Any]:
813
+ """关掉一个会话。
814
+
815
+ :param args: 协议参数
816
+ :returns: 关闭结果
817
+ """
818
+ session_id = args.get("sessionId")
819
+ _get_session(session_id)
820
+ _close_entry(session_id)
821
+ return {"sessionId": session_id, "closed": True}
822
+
823
+
824
+ def close_all_sessions() -> None:
825
+ """关掉全部会话。进程退出与 sidecar 重启时调用。
826
+
827
+ 浏览器会话留着不管的话,Chromium 进程会活过 sidecar 本身。
828
+ """
829
+ for session_id in list(_SESSIONS):
830
+ _close_entry(session_id)
831
+
832
+
833
+ # 爬虫放在独立模块:它要 import 本模块的 AdapterError,放进来就得绕开循环依赖。
834
+ from crawl import METHODS as CRAWL_METHODS # noqa: E402
835
+
836
+ METHODS.update(
837
+ {
838
+ "session.open": session_open,
839
+ "session.fetch": session_fetch,
840
+ "session.list": session_list,
841
+ "session.close": session_close,
842
+ }
843
+ )
844
+ METHODS.update(CRAWL_METHODS)