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

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