@jayyuen66/dsh-scrapling 0.0.3 → 0.1.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/py/adapters.py CHANGED
@@ -7,11 +7,13 @@ JSON 序列化的字典、把 Scrapling 的异常翻译成协议错误码。**
7
7
  引擎对照(``scrapling/fetchers/``)::
8
8
 
9
9
  Fetcher curl_cffi 静态抓取,只有 get/post/put/delete,没有 fetch()
10
- DynamicFetcher Playwright Chromium
11
10
  StealthyFetcher patchright Chromium
12
11
 
13
- 三者的返回都是 ``Response``,而 ``Response`` 继承 ``Selector``,所以抓完可以直接
14
- css/xpath。所有浏览器引擎都是**一次性 session**:每次调用开进程、结束即关。会话复用
12
+ Scrapling 0.5 删掉了纯 Playwright 后端(``DynamicFetcher``/``DynamicSession``),
13
+ 浏览器抓取只剩上面那一套,所以本模块不再有「普通浏览器 / 反检测浏览器」两档。
14
+
15
+ 两者的返回都是 ``Response``,而 ``Response`` 继承 ``Selector``,所以抓完可以直接
16
+ css/xpath。浏览器引擎是**一次性 session**:每次调用开进程、结束即关。会话复用
15
17
  必须走 ``*Session`` 类(``scrapling.fetchers`` 导出),不能靠本模块复用。
16
18
  """
17
19
 
@@ -24,6 +26,7 @@ import re
24
26
  import threading
25
27
  import uuid
26
28
  from datetime import datetime, timezone
29
+ from pathlib import Path
27
30
  from typing import Any, Callable
28
31
  from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
29
32
 
@@ -32,10 +35,10 @@ import guard
32
35
  # Scrapling 缺失时不要让整个 sidecar 起不来:桥接层会把它报成能力缺失,
33
36
  # 而不是让 Host 侧只看到一个「进程崩了」。
34
37
  try: # pragma: no cover —— 取决于运行环境是否装了 scrapling
35
- from scrapling.fetchers import DynamicFetcher, Fetcher, StealthyFetcher
38
+ from scrapling.fetchers import Fetcher, StealthyFetcher
36
39
  except ImportError: # pragma: no cover
37
40
  # 两个 ignore 各管一件事:misc 是「不能给类型赋值」,assignment 是「None 不是类」。
38
- Fetcher = DynamicFetcher = StealthyFetcher = None # type: ignore[misc,assignment]
41
+ Fetcher = StealthyFetcher = None # type: ignore[misc,assignment]
39
42
 
40
43
  SCRAPLING_AVAILABLE = Fetcher is not None
41
44
 
@@ -43,6 +46,10 @@ DEFAULT_EXTRACTION = "markdown"
43
46
  DEFAULT_TIMEOUT_SECONDS = 120.0
44
47
  DEFAULT_TIMEOUT_MS = 30_000
45
48
  DEFAULT_MAX_CONTENT_CHARS = 200_000
49
+ # 一次读网络历史最多回多少条、单条正文最多回多少字符。上游为每条响应体存下的是 1 MiB
50
+ # 量级,而这份摘要是给模型看的 —— 两个预算都由本包定,不由上游存了多少决定。
51
+ DEFAULT_NETWORK_ENTRIES = 50
52
+ DEFAULT_NETWORK_BODY_CHARS = 20_000
46
53
  EXTRACTION_TYPES = ("markdown", "html", "text")
47
54
  # adaptive 指纹库的文件名。**相对路径**:bridge 由宿主以部署侧的 dataDir 为工作目录拉起
48
55
  # (见 host.ts 的 sidecar env),相对路径正好把库落进 dataDir —— Scrapling 自己的默认值
@@ -216,26 +223,55 @@ def redact_url_secrets(raw: str) -> str:
216
223
  return urlunsplit((parsed.scheme, netloc, parsed.path, query, fragment))
217
224
 
218
225
 
219
- def _xhr_summary(responses: Any) -> list[dict[str, Any]]:
220
- """把 ``captured_xhr`` 压成轻量摘要。
226
+ def _network_summary(
227
+ network: Any, # noqa: ANN401 —— 上游的 NetworkRecorder
228
+ *,
229
+ pattern: str | None,
230
+ limit: int,
231
+ include_body: bool,
232
+ max_body_chars: int,
233
+ ) -> list[dict[str, Any]]:
234
+ """把会话网络历史压成给模型看的条目。
235
+
236
+ 只取 XHR/fetch 与 HTTP 错误(``include_static=False``):这条路径的用途是「页面数据来自
237
+ 接口而不是 DOM 时,找到那个接口」,静态资源只会把列表淹掉。
221
238
 
222
- XHR 响应体可能很大,全量塞回 Host 会把模型上下文撑爆;这里只给 URL、状态码与
223
- 字节数,模型自己决定要不要再对其中某个 URL 发一次抓取。
239
+ 正文只在显式要求时回传,并按 ``max_body_chars`` 逐条截断 —— 上游为每条响应体设了
240
+ 1 MiB、会话总量 20 MiB 的硬上限,那几十倍于模型预算的量级不该由「上游记了什么」决定
241
+ 「模型看见什么」。没存下正文时上游会在 ``meta['body_note']`` 里写原因,一并带出去,
242
+ 这样「这条接口没正文」与「这个接口本来就空」不是同一件事。
224
243
 
225
244
  URL 里的凭据型查询参数在这一层就脱敏:这份摘要是给模型看的,而模型用不上一个
226
245
  access token 却会把整条 URL 原样复述出去。
227
246
  """
228
247
  summary: list[dict[str, Any]] = []
229
- for item in responses or ():
248
+ try:
249
+ records = network.search(url_pattern=pattern, limit=limit, include_static=False)
250
+ except Exception: # noqa: BLE001 —— 记录器未启用或上游改了口径:当成「没有历史」
251
+ return summary
252
+ for item in records:
230
253
  try:
231
- summary.append(
232
- {
233
- "url": redact_url_secrets(str(item.url)),
234
- "status": item.status,
235
- "bytes": len(item.body),
236
- }
237
- )
238
- except Exception: # noqa: BLE001 —— 单条摘要失败不该拖垮整次抓取
254
+ meta = item.meta if isinstance(item.meta, dict) else {}
255
+ body = item.body
256
+ entry: dict[str, Any] = {
257
+ "url": redact_url_secrets(str(item.url)),
258
+ "status": item.status,
259
+ "bytes": len(body),
260
+ "method": str(meta.get("method") or item.request_headers.get("method") or "GET"),
261
+ "resourceType": str(meta.get("resource_type") or ""),
262
+ }
263
+ if not body:
264
+ note = meta.get("body_note")
265
+ if isinstance(note, str) and note:
266
+ entry["bodyNote"] = note
267
+ elif include_body:
268
+ text = body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body)
269
+ clipped, truncated = clip(text, max_body_chars)
270
+ entry["body"] = clipped
271
+ if truncated:
272
+ entry["bodyTruncated"] = True
273
+ summary.append(entry)
274
+ except Exception: # noqa: BLE001 —— 单条摘要失败不该拖垮整次读取
239
275
  continue
240
276
  return summary
241
277
 
@@ -404,11 +440,12 @@ def to_payload(
404
440
  else:
405
441
  content = response.markdown(css_selector=css_selector, main_content_only=main_content_only)
406
442
 
407
- clipped, truncated = clip(str(content), max_content_chars)
443
+ text = str(content)
408
444
  # 先剥再封顶:被剥掉的那几十 KB 不该占 max_content_chars 的额度,否则一页内联图就能把
409
445
  # 真正文挤出预算 —— 顺序反了等于白剥。
410
446
  if strip_inline_images:
411
- clipped = drop_data_uris(clipped, html=extraction_type == "html")
447
+ text = drop_data_uris(text, html=extraction_type == "html")
448
+ clipped, truncated = clip(text, max_content_chars)
412
449
  payload: dict[str, Any] = {
413
450
  "url": response.url,
414
451
  "status": response.status,
@@ -417,9 +454,6 @@ def to_payload(
417
454
  "truncated": truncated,
418
455
  "redirects": len(getattr(response, "history", ()) or ()),
419
456
  }
420
- captured = _xhr_summary(getattr(response, "captured_xhr", None))
421
- if captured:
422
- payload["xhr"] = captured
423
457
  return payload
424
458
 
425
459
 
@@ -511,6 +545,17 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
511
545
  # 发、对端收到空体,而回包上没有一行能看出这件事。
512
546
  params["json"] = _jsonable(body)
513
547
 
548
+ # Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
549
+ # 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
550
+ # 静态路径没有那一层,不在这里补就是「两道防线」只说了一半。判在写方法之后:那一条是
551
+ # 部署表态(非 GET 一律拒),与目标地址无关,不该被一条 URL_BLOCKED 盖掉。
552
+ # Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
553
+ # 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
554
+ # 静态路径没有那一层,不在这里补就是「两道防线」只说了一半。判在写方法之后:那一条是
555
+ # 部署表态(非 GET 一律拒),与目标地址无关,不该被一条 URL_BLOCKED 盖掉。
556
+ allowed, reason = guard.url_allowed(url)
557
+ if not allowed:
558
+ raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
514
559
  response = getattr(Fetcher, method.lower())(url, **params)
515
560
  return to_payload(
516
561
  response,
@@ -522,35 +567,34 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
522
567
  )
523
568
 
524
569
 
525
- def _xhr_pattern(args: dict[str, Any]) -> str | None:
526
- """取 XHR 捕获正则,并确认它编译得过。
570
+ def _url_pattern(args: dict[str, Any]) -> str | None:
571
+ """取网络历史的 URL 过滤正则,并确认它编译得过。
527
572
 
528
- 这个串由 :mod:`scrapling` 塞进响应处理器,对**每个**响应跑一次 ``re.search``。
529
- 写错一个字符时若不在这里拦下,报错会发生在浏览器的事件回调里 —— 表现是「页面抓到了,
530
- 但整次抓取冒出一串看不懂的错」,而用户看不出根因是自己正则写错了。
573
+ 上游 ``NetworkRecorder.search`` 拿它做 ``re.compile``,编译不过会抛 ValueError;那一层
574
+ 报的是「Invalid URL pattern: ...」,读的人看不出根因是自己正则写错了。所以在读历史
575
+ 之前就地判。
531
576
 
532
577
  :param args: 协议参数
533
- :returns: 正则文本;没给或为空串时给 None(Scrapling 据此不捕获)
578
+ :returns: 正则文本;没给或为空串时给 None(上游据此不过滤)
534
579
  :raises AdapterError: 正则编译不过
535
580
  """
536
- raw = args.get("captureXhrPattern")
581
+ raw = args.get("urlPattern")
537
582
  if not isinstance(raw, str) or not raw:
538
583
  return None
539
584
  try:
540
585
  re.compile(raw)
541
586
  except re.error as error:
542
- raise AdapterError("BAD_ARGS", f"captureXhrPattern is not a valid regex: {error}") from error
587
+ raise AdapterError("BAD_ARGS", f"urlPattern is not a valid regex: {error}") from error
543
588
  return raw
544
589
 
545
590
 
546
- # ``DynamicSession.fetch`` / ``StealthySession.fetch`` 只认这份名单(上游
547
- # ``engines/_browsers/_validators.py`` 的 ``_fetch_params`` 字段,外加实现自己 ``pop``
548
- # 出来的 ``proxy``)。名单之外的键**不报错、不生效**:``validate_fetch`` 只从 kwargs 里挑
549
- # 认识的字段,其余原样丢掉。
591
+ # ``StealthySession.fetch`` 只认这份名单(上游 ``engines/_browsers/_validators.py`` 的
592
+ # ``_fetch_params`` 字段,外加实现自己 ``pop`` 出来的 ``proxy``)。名单之外的键**不报错、
593
+ # 不生效**:``validate_fetch`` 只从 kwargs 里挑认识的字段,其余原样丢掉。
550
594
  #
551
595
  # 所以会话路径上必须按层级分家:这些键在 fetch 层传了等于没传,唯一生效的地方是会话构造
552
- # (``DynamicSession(...)`` / ``StealthySession(...)``)。``py/tests/contract_probe.py``
553
- # 会拿真实上游校验这张表与 ``_fetch_params`` 是否仍然一致。
596
+ # (``StealthySession(...)``)。``py/tests/contract_probe.py`` 会拿真实上游校验这张表与
597
+ # ``_fetch_params`` 是否仍然一致。
554
598
  FETCH_LEVEL_KEYS = frozenset(
555
599
  {
556
600
  "blocked_domains",
@@ -561,6 +605,7 @@ FETCH_LEVEL_KEYS = frozenset(
561
605
  "network_idle",
562
606
  "page_action",
563
607
  "page_setup",
608
+ "pierce_shadow",
564
609
  "proxy",
565
610
  "selector_config",
566
611
  "solve_cloudflare",
@@ -575,39 +620,78 @@ FETCH_LEVEL_KEYS = frozenset(
575
620
  # 要么就根本别发。
576
621
  #
577
622
  # 这张表是**上游的事实**而不是本包的透传清单:`max_pages` / `retries` / `retry_delay` 上游
578
- # 确实是构造期参数,但本包一个都不发(各自的部署设置在 Config 里没有对应字段),所以它们在
623
+ # 确实是构造期参数,但本包一个都不发(各自没有对应的部署设置),所以它们在
579
624
  # `_browser_params` 的产物里根本不出现 —— 过滤器对它们是无操作,留着是为了让
580
625
  # `py/tests/contract_probe.py` 能拿整张表与上游字段面比对,而不是只比对我们用到的那几项。
626
+ #
627
+ # `record_requests` / `max_recorded_requests` 是 0.5 用会话网络历史替代 `capture_xhr` 之后
628
+ # 新增的两枚:它们**只**在构造期生效,逐次 fetch 传等于没传(这正是那个替代方案的核心)。
581
629
  SESSION_ONLY_KEYS = frozenset(
582
630
  {
631
+ "allow_webgl",
583
632
  "block_ads",
584
- "capture_xhr",
633
+ "block_webrtc",
585
634
  "cdp_url",
635
+ "dns_over_https",
586
636
  "executable_path",
587
637
  "headless",
638
+ "hide_canvas",
639
+ "init_script",
588
640
  "locale",
589
641
  "max_pages",
642
+ "max_recorded_requests",
643
+ "real_chrome",
644
+ "record_requests",
590
645
  "retries",
591
646
  "retry_delay",
592
647
  "timezone_id",
593
648
  "useragent",
649
+ "user_data_dir",
594
650
  }
595
651
  )
596
652
 
597
653
 
598
- def _browser_params(args: dict[str, Any], url: str, *, stealth: bool = False, level: str = "session") -> dict[str, Any]:
654
+ # 部署命名空间里的浏览器旋钮:源键 → 引擎参数名 → 期望类型。类型逐项写死,是因为这一层
655
+ # 与模型入参走同一条通道而它承载的是**部署表态**:类型错了静默生效比报错更糟(例如
656
+ # maxRecordedRequests 收到字符串,上游会拿它当容量直接炸会话构造)。
657
+ _DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
658
+ ("browserExecutablePath", "executable_path", str),
659
+ ("browserCdpUrl", "cdp_url", str),
660
+ ("browserInitScript", "init_script", str),
661
+ ("browserRealChrome", "real_chrome", bool),
662
+ ("browserDnsOverHttps", "dns_over_https", bool),
663
+ ("recordRequests", "record_requests", bool),
664
+ ("maxRecordedRequests", "max_recorded_requests", int),
665
+ )
666
+
667
+
668
+ def _knob_value(kind: type, value: Any) -> Any: # noqa: ANN401 —— 收的是部署载荷里的任意 JSON 值
669
+ """按声明的类型收下一枚部署旋钮值;类型不符给 None。
670
+
671
+ 类型必须真的对得上:这一层承载的是部署表态,把字符串塞进一个整数旋钮(或反过来)时
672
+ 静默生效比报错更糟 —— 上游会拿它当参数,直接把会话构造炸掉。
673
+ """
674
+ if kind is str:
675
+ return value if isinstance(value, str) and value else None
676
+ if kind is bool:
677
+ return value if isinstance(value, bool) else None
678
+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:
679
+ return value
680
+ return None
681
+
682
+
683
+ def _browser_params(args: dict[str, Any], url: str, *, level: str = "session") -> dict[str, Any]:
599
684
  """浏览器抓取的公共参数。
600
685
 
601
- ``level`` 决定这份参数**送给哪一层**:一次性抓取(``DynamicFetcher.fetch``)与会话构造
686
+ ``level`` 决定这份参数**送给哪一层**:一次性抓取(``StealthyFetcher.fetch``)与会话构造
602
687
  收的是完整的会话级参数面;而会话内每次 fetch 只认 ``FETCH_LEVEL_KEYS`` 那十几个键,其余
603
688
  一律被上游静默丢弃(见上面那张表的注释)。所以 ``level="fetch"`` 时按名单过滤 ——
604
689
  宁可少发一个键,也不要发一个「看起来在生效其实没生效」的键:后者的排查成本是整条链路。
605
690
 
606
- ``extra_flags`` 只在非 stealth 那一套上加:上游 ``_base.py`` 算启动参数时
607
- ``config.extra_flags`` **优先于**内部递进来的 53 条 ``STEALTH_ARGS``,于是给
608
- ``StealthyFetcher`` / ``StealthySession`` 传这条会把整套反检测参数换掉,连
609
- ``block_webrtc`` 自己那两条也一起没。stealth 侧的 WebRTC 防泄露走 ``block_webrtc``
610
- 开关本身(两条 flag 由上游下),Playwright 侧没有这个开关,只能进 ``extra_flags``。
691
+ WebRTC 防泄露只走 ``block_webrtc`` 开关本身。0.4.15 时代这里还要往启动参数里塞两条
692
+ flag,因为那时的 ``config.extra_flags`` 会**顶掉**内建那套反检测 flag;0.5 把它改成
693
+ 叠加(上游 PR #430),而浏览器抓取也只剩 patchright 一套,``block_webrtc`` 一条开关
694
+ 两件事都覆盖,于是那条绕行路径连同它要回避的坑一起消失。
611
695
 
612
696
  ``block_ads`` 由部署设置决定,可以打开:它并不会与 SSRF 守卫抢 handler。
613
697
  上游把 ``block_ads`` 折进**同一个** ``blocked_domains``(engines/_browsers/
@@ -619,16 +703,15 @@ def _browser_params(args: dict[str, Any], url: str, *, stealth: bool = False, le
619
703
  ``blocked_domains`` / ``disable_resources`` 仍固定关闭:本包没有对应的部署设置,
620
704
  而打开它们同样只是给上游那个 handler 加料,不会削弱守卫。
621
705
 
622
- 代理在这里显式交给引擎,是三条抓取路径里唯一必须这么做的一条:Chromium 不读
706
+ 代理在这里显式交给引擎,是浏览器这条路径上唯一必须这么做的地方:Chromium 不读
623
707
  ``HTTP_PROXY``/``ALL_PROXY``,只读系统代理设置,于是一台只在 shell 里 export 过代理
624
- 的机器上静态抓取走代理、浏览器抓取却直连。传 ``proxy`` 给 ``DynamicFetcher.fetch`` /
625
- ``StealthyFetcher.fetch`` 时它落进**会话**配置(fetchers/*.py 里是
626
- ``DynamicSession(**kwargs)``),进 ``launch_persistent_context`` 的 context 选项 ——
627
- 所以是一次抓取一个 context,与一次性会话的既有形态一致,且不会丢 cookie。
708
+ 的机器上静态抓取走代理、浏览器抓取却直连。传 ``proxy`` 给 ``StealthyFetcher.fetch``
709
+ 时它落进**会话**配置(fetchers/stealth_chrome.py 里是 ``StealthySession(**kwargs)``),
710
+ 进 ``launch_persistent_context`` 的 context 选项 —— 所以是一次抓取一个 context,
711
+ 与一次性会话的既有形态一致,且不会丢 cookie。
628
712
 
629
713
  :param args: 协议参数
630
714
  :param url: 本次抓取的地址,用来定代理
631
- :param stealth: 走的是 patchright 那一套吗
632
715
  :param level: ``session``(会话级全量)或 ``fetch``(只发 fetch 层认得的键)
633
716
  :returns: 引擎参数
634
717
  """
@@ -642,11 +725,6 @@ def _browser_params(args: dict[str, Any], url: str, *, stealth: bool = False, le
642
725
  proxy = guard.browser_proxy(url)
643
726
  if proxy is not None:
644
727
  params["proxy"] = proxy
645
- # WebRTC 能绕过代理直接发 UDP,页面里一句 STUN 就能问出访客的真实出口 IP。
646
- # 走代理时那条信息本就不该泄露:patchright 有 block_webrtc 开关(上游自己下两条
647
- # flag),Playwright 没有,只能从启动参数进去 —— 见上面 extra_flags 的说明。
648
- if not stealth:
649
- params["extra_flags"] = list(guard.WEBRTC_NO_LEAK_FLAGS)
650
728
  if args.get("networkIdle"):
651
729
  params["network_idle"] = True
652
730
  for key, name in (
@@ -659,23 +737,15 @@ def _browser_params(args: dict[str, Any], url: str, *, stealth: bool = False, le
659
737
  value = args.get(key)
660
738
  if isinstance(value, str) and value:
661
739
  params[name] = value
662
- # XHR 捕获正则单独走一道:它是用户手写的正则,编译不过要在发车前就报出来,
663
- # 而不是等它在浏览器的事件回调里炸。
664
- xhr_pattern = _xhr_pattern(args)
665
- if xhr_pattern is not None:
666
- params["capture_xhr"] = xhr_pattern
667
- # 浏览器二进制路径与 CDP 端点只从 deployment 命名空间取,不在上面的模型可见透传表里:
668
- # executable_path 等于「让 Chromium 去执行这个文件」,cdp_url 等于「把浏览器交给这个
669
- # 调试端点」,两者都是部署级的强能力,但绝不能由模型入参驱动。Host 侧对应的两枚设置
670
- # 同样是非 volatile 的部署级字段(不进设置卡)。
740
+ # open shadow root 里的内容默认不进正文 —— 页面把那部分内容藏在 shadow 里时,
741
+ # 不打开这个开关在 HTML 里根本看不到它。
742
+ if args.get("pierceShadow"):
743
+ params["pierce_shadow"] = True
671
744
  deployment = args.get("deployment")
672
745
  if isinstance(deployment, dict):
673
- for source, target in (
674
- ("browserExecutablePath", "executable_path"),
675
- ("browserCdpUrl", "cdp_url"),
676
- ):
677
- value = deployment.get(source)
678
- if isinstance(value, str) and value:
746
+ for source, target, kind in _DEPLOYMENT_KNOBS:
747
+ value = _knob_value(kind, deployment.get(source))
748
+ if value is not None:
679
749
  params[target] = value
680
750
  wait_ms = args.get("waitMs")
681
751
  if isinstance(wait_ms, (int, float)) and not isinstance(wait_ms, bool) and wait_ms > 0:
@@ -683,59 +753,53 @@ def _browser_params(args: dict[str, Any], url: str, *, stealth: bool = False, le
683
753
  extra_headers = _string_map(args.get("extraHeaders"), "extraHeaders")
684
754
  if extra_headers is not None:
685
755
  params["extra_headers"] = extra_headers
686
- if stealth:
687
- # 这四条只在 stealth 的参数面里(StealthSession / StealthFetchParams 只认
688
- # solve_cloudflare),所以一次性抓取与会话构造都从这里进,避免两处写法漂移。
689
- params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
690
- params["hide_canvas"] = bool(args.get("hideCanvas", False))
691
- # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
692
- # 插件正是为了不泄露它。
693
- params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or "proxy" in params
694
- params["allow_webgl"] = bool(args.get("allowWebgl", True))
756
+ # 四条反检测参数只在浏览器那套的参数面里。solve_cloudflare 逐次 fetch 也认,其余三条
757
+ # 只有会话构造认 —— 两层的分家由上面那两张名单做。
758
+ params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
759
+ params["hide_canvas"] = bool(args.get("hideCanvas", False))
760
+ # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
761
+ # 插件正是为了不泄露它。
762
+ params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or "proxy" in params
763
+ params["allow_webgl"] = bool(args.get("allowWebgl", True))
695
764
  if level == "fetch":
696
765
  return {key: value for key, value in params.items() if key in FETCH_LEVEL_KEYS}
697
766
  return params
698
767
 
699
768
 
700
- def _session_browser_params(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
769
+ def _session_browser_params(args: dict[str, Any]) -> dict[str, Any]:
701
770
  """会话构造期的浏览器参数:只收**只有开场才生效**的那些键。
702
771
 
703
- 会话内每次 fetch 传 ``capture_xhr`` / ``block_ads`` / ``executable_path`` / ``cdp_url`` /
704
- ``locale`` / ``timezone_id`` / ``useragent`` / ``headless`` 都会被 ``validate_fetch``
705
- 丢掉,于是设置卡上这些旋钮对会话路径完全不生效 —— 而且不报错。这里把它们挪到唯一
706
- 生效的位置。
772
+ 会话内每次 fetch 传 ``block_ads`` / ``record_requests`` / ``executable_path`` /
773
+ ``cdp_url`` / ``locale`` / ``timezone_id`` / ``useragent`` / ``headless`` 都会被
774
+ ``validate_fetch`` 丢掉,于是设置卡上这些旋钮对会话路径完全不生效 —— 而且不报错。
775
+ 这里把它们挪到唯一生效的位置。
707
776
 
708
777
  代理不在这张表里:会话的代理在开场时按 ``default_proxy()`` 定一次(中途换代理要新建
709
778
  context,等于丢掉 cookie 与登录态,而那正是会话存在的理由),见 :func:`_make_session`。
710
779
 
711
780
  :param args: 协议参数
712
- :param stealth: 走的是 patchright 那一套吗
713
781
  :returns: 会话构造参数
714
782
  """
715
783
  # url 只用来定代理,而会话级代理另在 _make_session 里定,这里给空串即可。
716
- full = _browser_params(args, "", stealth=stealth)
784
+ full = _browser_params(args, "")
717
785
  # timeout 在两层都认,会话构造必须带上它,否则整个会话回落到上游的 30s 页面超时。
718
786
  keep = SESSION_ONLY_KEYS | {"timeout"}
719
- if stealth:
720
- keep |= {"allow_webgl", "hide_canvas", "block_webrtc", "solve_cloudflare"}
721
787
  return {key: value for key, value in full.items() if key in keep}
722
788
 
723
789
 
724
- def render(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
725
- """浏览器抓取。``stealth`` 为真时走 patchright 引擎。
790
+ def render(args: dict[str, Any]) -> dict[str, Any]:
791
+ """浏览器抓取(patchright)。0.5 起这是唯一的浏览器引擎。
726
792
 
727
793
  :param args: 协议参数
728
- :param stealth: 是否用 StealthyFetcher
729
794
  :returns: 归一后的载荷
730
795
  """
731
- engine = StealthyFetcher if stealth else DynamicFetcher
732
- _require(engine)
796
+ _require(StealthyFetcher)
733
797
  url = _url(args)
734
798
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
735
799
 
736
- params = _browser_params(args, url, stealth=stealth)
800
+ params = _browser_params(args, url)
737
801
  params["page_setup"] = page_setup
738
- response = engine.fetch(url, **params)
802
+ response = StealthyFetcher.fetch(url, **params)
739
803
  return to_payload(
740
804
  response,
741
805
  extraction_type=extraction_type,
@@ -746,6 +810,114 @@ def render(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
746
810
  )
747
811
 
748
812
 
813
+ def _network_read(args: dict[str, Any]) -> tuple[str | None, int, bool, int]:
814
+ """抽出「读网络历史」的四个参数并校验。
815
+
816
+ :param args: 协议参数
817
+ :returns: (URL 过滤正则, 条数上限, 是否回传正文, 单条正文预算)
818
+ """
819
+ return (
820
+ _url_pattern(args),
821
+ _positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
822
+ bool(args.get("includeBody", False)),
823
+ _positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
824
+ )
825
+
826
+
827
+ def _capture_once(
828
+ args: dict[str, Any],
829
+ *,
830
+ url: str,
831
+ pattern: str | None,
832
+ entries: int,
833
+ include_body: bool,
834
+ body_chars: int,
835
+ ) -> tuple[Any, list[dict[str, Any]]]:
836
+ """在一个临时会话里抓一次,并把这次抓取记下的网络条目一起读出来。
837
+
838
+ 记录开关在这条路径上**不跟随部署设置**:这个方法的全部意义就是那份历史,不开记录
839
+ 等于白抓一次。容量(``max_recorded_requests``)仍由部署设置决定。
840
+
841
+ :param args: 协议参数
842
+ :param url: 要抓的地址
843
+ :param pattern: URL 过滤正则
844
+ :param entries: 最多回多少条
845
+ :param include_body: 是否回传响应体
846
+ :param body_chars: 单条正文的字符预算
847
+ :returns: (response, 网络条目)
848
+ """
849
+ from scrapling.fetchers import StealthySession
850
+
851
+ session_params = _session_browser_params(args)
852
+ session_params["record_requests"] = True
853
+ fetch_params = _browser_params(args, url, level="fetch")
854
+ # 会话的代理在构造期就定死了,逐次 fetch 再给一次只会被上游丢掉。
855
+ fetch_params.pop("proxy", None)
856
+ fetch_params["page_setup"] = page_setup
857
+ session = StealthySession(**session_params)
858
+ try:
859
+ session.start()
860
+ response = session.fetch(url, **fetch_params)
861
+ records = _network_summary(
862
+ session.network,
863
+ pattern=pattern,
864
+ limit=entries,
865
+ include_body=include_body,
866
+ max_body_chars=body_chars,
867
+ )
868
+ finally:
869
+ # 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
870
+ with contextlib.suppress(Exception):
871
+ session.close()
872
+ return response, records
873
+
874
+
875
+ def capture(args: dict[str, Any]) -> dict[str, Any]:
876
+ """抓一个 URL,并把这次抓取记下的 XHR/fetch 一起交回去。
877
+
878
+ 0.5 删掉了 ``capture_xhr``:一次性 fetch 的响应上不再挂 XHR 列表,替代方案是「会话
879
+ 构造期打开 ``record_requests``,之后读 ``session.network``」。所以这条路径自己起一个
880
+ 会话 —— 但对模型仍然是一次动作:就地开、就地关,不进会话注册表,既不占会话名额,
881
+ 也不会把 cookie 留到下一次调用。
882
+
883
+ :param args: 协议参数
884
+ :returns: 页面载荷,外加这次抓取记下的网络条目
885
+ :raises AdapterError: 参数非法,或抓取失败
886
+ """
887
+ _require(StealthyFetcher)
888
+ url = _url(args)
889
+ extraction_type, css_selector, main_content_only, limit = _extraction(args)
890
+ pattern, entries, include_body, body_chars = _network_read(args)
891
+
892
+ # 整条链路投到一条专属线程上:patchright 的同步 API 与创建它的线程绑定(greenlet),
893
+ # 而 bridge 的 worker 线程是「谁抢到帧谁处理」,所以这里建一条自己的、用完就收。
894
+ worker = _SessionWorker()
895
+ try:
896
+ response, records = worker.run(
897
+ lambda: _capture_once(
898
+ args,
899
+ url=url,
900
+ pattern=pattern,
901
+ entries=entries,
902
+ include_body=include_body,
903
+ body_chars=body_chars,
904
+ )
905
+ )
906
+ finally:
907
+ worker.stop()
908
+
909
+ payload = to_payload(
910
+ response,
911
+ extraction_type=extraction_type,
912
+ css_selector=css_selector,
913
+ main_content_only=main_content_only,
914
+ max_content_chars=limit,
915
+ strip_inline_images=_strip_inline_images(args),
916
+ )
917
+ payload["xhr"] = records
918
+ return payload
919
+
920
+
749
921
  def _fake_response(html: str, url: str, status: int) -> Any:
750
922
  """造一个不带网络的 ``Response``,给离线抽取用。"""
751
923
  from scrapling.engines.toolbelt.custom import Response
@@ -894,15 +1066,15 @@ def _scrapling_version() -> str:
894
1066
  def _probe_browser(module_name: str) -> bool:
895
1067
  """起一次浏览器再关掉,确认浏览器二进制真的可用。
896
1068
 
897
- 为什么直接用 Playwright/patchright 而不走 ``engine.fetch``:Scrapling 的 fetch 会在
898
- ``page.goto`` 返回 None 时抛 "Failed to get response",而 ``data:`` 与 ``about:blank``
899
- 这类 URL 恰好不产生 response。拿它们当探针 URL 会稳定地假失败,还会被 ``retries``
900
- 放大成几秒钟的重试风暴。
1069
+ 为什么直接用引擎而不走 ``engine.fetch``:Scrapling 的 fetch 会在 ``page.goto`` 返回
1070
+ None 时抛 "Failed to get response",而 ``data:`` 与 ``about:blank`` 这类 URL 恰好不
1071
+ 产生 response。拿它们当探针 URL 会稳定地假失败,还会被 ``retries`` 放大成几秒钟的重试
1072
+ 风暴。
901
1073
 
902
- 要验的其实只有一件事:**浏览器二进制装没装**。``playwright install chromium`` 与
903
- patchright 各自管理浏览器,少任一个都会在真正调用时才炸,所以两个引擎都要单独探。
1074
+ 要验的其实只有一件事:**浏览器二进制装没装**。``patchright install chromium`` 装的是
1075
+ patchright 自己那一份,缺了它会在真正调用时才炸。
904
1076
 
905
- :param module_name - ``"playwright.sync_api"`` 或 ``"patchright.sync_api"``
1077
+ :param module_name - 要探的引擎模块名,目前只有 ``"patchright.sync_api"``
906
1078
  :returns: 浏览器能否启动
907
1079
  """
908
1080
  import importlib
@@ -924,7 +1096,6 @@ def capabilities() -> dict[str, Any]:
924
1096
  "static": SCRAPLING_AVAILABLE,
925
1097
  "extract": SCRAPLING_AVAILABLE,
926
1098
  "browser": False,
927
- "stealth": False,
928
1099
  # 写方法这一档**与 scrapling 在不在无关**:它是部署表态,而排障的人得能一眼看出
929
1100
  # 「这台到底许不许写」,而不是等到发 POST 被拒才发现环境里少一个变量。
930
1101
  "writeMethods": guard.ALLOW_WRITE_METHODS,
@@ -932,8 +1103,9 @@ def capabilities() -> dict[str, Any]:
932
1103
  if not SCRAPLING_AVAILABLE:
933
1104
  return report
934
1105
  report["version"] = _scrapling_version()
935
- report["browser"] = _probe_browser("playwright.sync_api")
936
- report["stealth"] = _probe_browser("patchright.sync_api")
1106
+ # 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
1107
+ # 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的口径已经没有第二个引擎可标。
1108
+ report["browser"] = _probe_browser("patchright.sync_api")
937
1109
  # 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
938
1110
  # server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
939
1111
  report["proxy"] = guard.proxy_settings()
@@ -944,8 +1116,8 @@ METHODS = {
944
1116
  "ping": lambda _args: {"pong": True},
945
1117
  "capabilities": lambda _args: capabilities(),
946
1118
  "fetch": fetch,
947
- "render": lambda args: render(args, stealth=False),
948
- "stealth_fetch": lambda args: render(args, stealth=True),
1119
+ "render": render,
1120
+ "capture": capture,
949
1121
  "extract": extract,
950
1122
  "select": select,
951
1123
  }
@@ -958,18 +1130,19 @@ METHODS = {
958
1130
  # 会话把这份状态留在 sidecar 进程里跨请求复用 —— 这是 Scrapling 相对
959
1131
  # 「每次调用都重新来」最实用的一块。
960
1132
  #
961
- # 三种类型与 Scrapling 的一一对应:
1133
+ # 两种类型与 Scrapling 的一一对应:
962
1134
  # static -> FetcherSession(curl_cffi)
963
- # browser -> DynamicSession(Playwright)
964
- # stealth -> StealthySession(patchright)
1135
+ # stealth -> StealthySession(patchright,0.5 起唯一的浏览器引擎)
965
1136
  # ---------------------------------------------------------------------------
966
1137
 
967
1138
  _SESSION_CLASSES = {
968
1139
  "static": "FetcherSession",
969
- "browser": "DynamicSession",
970
1140
  "stealth": "StealthySession",
971
1141
  }
972
1142
 
1143
+ # 吃内存的那几类(每个都是一个真实浏览器进程):名额与专属执行线程都按它判。
1144
+ _BROWSER_KINDS = frozenset({"stealth"})
1145
+
973
1146
  # 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
974
1147
  # 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>, "lock": Lock,
975
1148
  # "worker": _SessionWorker | None};正在构造中的条目只有
@@ -983,11 +1156,11 @@ _SESSIONS: dict[str, dict[str, Any]] = {}
983
1156
  # 跑的 Chromium),名额判完再开等于没判。
984
1157
  _SESSION_LOCK = threading.Lock()
985
1158
 
986
- # 同开几个会话。browser/stealth 每开一个就是一个真实的 Chromium 进程,而 sessionType 是
1159
+ # 同开几个会话。浏览器会话每开一个就是一个真实的 Chromium 进程,而 sessionType 是
987
1160
  # **模型可选**的参数 —— 不设上限的话,「开 → 不关」重复几次就能把机器的内存吃光。
988
1161
  # 因此在登记之前就判,而不是指望模型记得调 session_close。
989
1162
  MAX_SESSIONS = 8
990
- # 其中最多几个可以是吃内存的那两种。static 只是连接池,便宜得多。
1163
+ # 其中最多几个可以是吃内存的浏览器会话。static 只是连接池,便宜得多。
991
1164
  MAX_BROWSER_SESSIONS = 3
992
1165
 
993
1166
 
@@ -1078,35 +1251,32 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
1078
1251
  # wrapper 要留在登记条目里,close 时才能 __exit__。
1079
1252
  return logic, wrapper
1080
1253
 
1081
- from scrapling.fetchers import DynamicSession, StealthySession
1254
+ from scrapling.fetchers import StealthySession
1082
1255
 
1083
- stealth = kind == "stealth"
1084
- # 只有开场才生效的那些设置(capture_xhr / block_ads / headless / locale /
1256
+ # 只有开场才生效的那些设置(block_ads / record_requests / headless / locale /
1085
1257
  # timezone_id / useragent / executable_path / cdp_url / timeout)必须在这里进会话:
1086
1258
  # fetch 层传过去会被 validate_fetch 静默丢掉(见 FETCH_LEVEL_KEYS)。
1087
- common: dict[str, Any] = _session_browser_params(args, stealth=stealth)
1259
+ common: dict[str, Any] = _session_browser_params(args)
1260
+ # 每会话的记录开关:模型可以为这一次会话打开记录(部署侧那枚是默认值)。记录不改变
1261
+ # 请求行为,只是把已经发生的流量留在内存里,所以它不是部署级强能力。
1262
+ if args.get("recordNetwork") is True:
1263
+ common["record_requests"] = True
1088
1264
  # 会话开的时候还不知道要访问哪个主机,所以按「配了代理就用代理」定档;显式填过
1089
1265
  # proxyBypass 的主机在会话里也跟着走代理 —— 见上面的取舍说明。
1090
1266
  proxy = guard.split_proxy(guard.default_proxy())
1091
1267
  if proxy is not None:
1092
1268
  common["proxy"] = proxy
1093
- if not stealth:
1094
- # Playwright 那边没有 block_webrtc 开关,只能从启动参数进去。stealth 侧**不能**
1095
- # 走这条路:上游算 flag 时 config.extra_flags 优先于内部那 53 条 STEALTH_ARGS,
1096
- # 传了就整段替换(连 block_webrtc 自己的两条也一起没),见 _browser_params。
1097
- common["extra_flags"] = list(guard.WEBRTC_NO_LEAK_FLAGS)
1098
- if stealth:
1099
- # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
1100
- # 插件正是为了不泄露它。
1101
- #
1102
- # 判据**只能**是这里算出的那份 proxy:`_session_browser_params` 里那条是按
1103
- # `browser_proxy("")` 定的,而空 URL 没有主机名,绕过清单里的任何主机名条目都命中
1104
- # 不了它 —— 只有 `default_proxy()` 认的那个「整台机器直连」的 `*` 例外。于是
1105
- # `proxyBypass=*` 时上面那条会算出「有代理」并把 block_webrtc 钉成真,而会话其实
1106
- # 是直连的:模型明确填了 blockWebrtc=false 也会被静默盖掉(正是本轮在消灭的那类毛病)。
1107
- # 这里整体重写,不继承那份结论。
1108
- common["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
1109
- session: DynamicSession | StealthySession = StealthySession(**common) if stealth else DynamicSession(**common)
1269
+ # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
1270
+ # 插件正是为了不泄露它。
1271
+ #
1272
+ # 判据**只能**是这里算出的那份 proxy:`_session_browser_params` 里那条是按
1273
+ # `browser_proxy("")` 定的,而空 URL 没有主机名,绕过清单里的任何主机名条目都命中
1274
+ # 不了它 —— 只有 `default_proxy()` 认的那个「整台机器直连」的 `*` 例外。于是
1275
+ # `proxyBypass=*` 时上面那条会算出「有代理」并把 block_webrtc 钉成真,而会话其实
1276
+ # 是直连的:模型明确填了 blockWebrtc=false 也会被静默盖掉。
1277
+ # 这里整体重写,不继承那份结论。
1278
+ common["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
1279
+ session = StealthySession(**common)
1110
1280
  session.start()
1111
1281
  return session, session
1112
1282
 
@@ -1128,8 +1298,8 @@ def _enforce_session_limits(kind: str) -> None:
1128
1298
  f"{len(_SESSIONS)} sessions are already open (limit {MAX_SESSIONS}); "
1129
1299
  "close one with session.close before opening another",
1130
1300
  )
1131
- if kind in ("browser", "stealth"):
1132
- browsers = sum(1 for entry in _SESSIONS.values() if entry["type"] in ("browser", "stealth"))
1301
+ if kind in _BROWSER_KINDS:
1302
+ browsers = sum(1 for entry in _SESSIONS.values() if entry["type"] in _BROWSER_KINDS)
1133
1303
  if browsers >= MAX_BROWSER_SESSIONS:
1134
1304
  raise AdapterError(
1135
1305
  "SESSION_LIMIT",
@@ -1234,31 +1404,32 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1234
1404
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
1235
1405
  url = _url(args)
1236
1406
 
1237
- # 一份会话同一时刻只服务一个请求:static 靠 entry 锁,browser/stealth 靠属主线程
1238
- # 天然串行。两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步
1239
- # API 靠 greenlet 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个
1240
- # 会话」。表现是看不懂的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
1407
+ # 一份会话同一时刻只服务一个请求:static 靠 entry 锁,浏览器会话靠属主线程天然串行。
1408
+ # 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
1409
+ # 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个会话」。表现是看不懂
1410
+ # 的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
1241
1411
  try:
1242
1412
  if entry["type"] == "static":
1243
1413
  with entry["lock"]:
1414
+ # 与一次性 fetch 同一条复判:static 会话的请求不经过浏览器的 page.route,
1415
+ # 少了这一道,「Host 判完 → curl_cffi 自己再解析」之间就是敞开的。
1416
+ allowed, reason = guard.url_allowed(url)
1417
+ if not allowed:
1418
+ raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
1244
1419
  response = session.get(url, **_static_params(args, url))
1245
1420
  else:
1246
1421
  # 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
1247
1422
  # 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
1248
1423
  #
1249
1424
  # level="fetch" 是这条路径的关键:会话内每次 fetch 只认 FETCH_LEVEL_KEYS,
1250
- # 其余键(capture_xhr / block_ads / headless / locale / timezone_id /
1251
- # useragent / executable_path / cdp_url,以及 stealth 的 hide_canvas /
1252
- # block_webrtc / allow_webgl)会被 validate_fetch **静默丢掉**。那些设置已经
1253
- # 在 session.open 时经 _session_browser_params 进过会话了,这里再发一遍只会
1254
- # 制造「拧了没反应」的假象。
1255
- params = _browser_params(args, url, stealth=entry["type"] == "stealth", level="fetch")
1425
+ # 其余键(block_ads / record_requests / headless / locale / timezone_id /
1426
+ # useragent / executable_path / cdp_url,以及 hide_canvas / block_webrtc /
1427
+ # allow_webgl)会被 validate_fetch **静默丢掉**。那些设置已经在 session.open
1428
+ # 时经 _session_browser_params 进过会话了,这里再发一遍只会制造「拧了没反应」
1429
+ # 的假象。
1430
+ params = _browser_params(args, url, level="fetch")
1256
1431
  params.pop("proxy", None)
1257
1432
  params["page_setup"] = page_setup
1258
- if entry["type"] == "stealth":
1259
- # solve_cloudflare 是 stealth 会话 fetch 唯一还认的 stealth 键(其余两条
1260
- # flag 类设置在构造期定死),所以仍然按本次入参给。
1261
- params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
1262
1433
  # headers / retries 只有 static 那条路读得懂(_static_params):浏览器会话的请求头
1263
1434
  # 是 extra_headers,重试则是会话构造期的 config.retries。传错了不生效,而上游连
1264
1435
  # 一声都不抱怨 —— 这里替它抱怨,因为「拧了没反应」正是本包在消灭的那类故障,而
@@ -1276,7 +1447,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1276
1447
  # 投递到属主线程执行:greenlet 绑定在那里(见 _SessionWorker)。排队期间调用
1277
1448
  # 线程原地等 —— 并发的 fetch 因此天然串行,entry 锁对浏览器会话是多余的。
1278
1449
  worker: _SessionWorker | None = entry["worker"]
1279
- if worker is None: # pragma: no cover —— browser/stealth 条目必有属主线程
1450
+ if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1280
1451
  raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
1281
1452
  response = worker.run(lambda: session.fetch(url, **params))
1282
1453
  except AdapterError:
@@ -1369,6 +1540,119 @@ def session_close(args: dict[str, Any]) -> dict[str, Any]:
1369
1540
  return {"sessionId": session_id, "closed": True}
1370
1541
 
1371
1542
 
1543
+ def session_network(args: dict[str, Any]) -> dict[str, Any]:
1544
+ """读一个已开会话记下的网络历史。
1545
+
1546
+ 记录是**会话构造期**的开关:部署侧那枚是默认值,模型可以在 ``session.open`` 时用
1547
+ ``recordNetwork`` 为本会话打开。逐次 fetch 传不上去(见 SESSION_ONLY_KEYS)。所以没开
1548
+ 记录时报一句可读的错,而不是回一个空列表 —— 「没开记录」与「这次没抓到接口」是两件
1549
+ 要采取不同行动的事。
1550
+
1551
+ :param args: 协议参数
1552
+ :returns: 命中的网络条目
1553
+ :raises AdapterError: 会话不存在 / 静态会话没有网络历史 / 这个会话没开记录
1554
+ """
1555
+ session_id = args.get("sessionId")
1556
+ entry = _get_session(session_id)
1557
+ if entry["type"] == "static":
1558
+ raise AdapterError("BAD_ARGS", "static sessions keep no network history")
1559
+ pattern, entries, include_body, body_chars = _network_read(args)
1560
+ recorder = getattr(entry["session"], "network", None)
1561
+ if recorder is None or not getattr(recorder, "enabled", False):
1562
+ raise AdapterError(
1563
+ "NETWORK_NOT_RECORDED",
1564
+ "this session is not recording requests; open it with recordNetwork:true "
1565
+ "(or set the deployment knob recordRequests) to keep its history",
1566
+ )
1567
+ worker: _SessionWorker | None = entry["worker"]
1568
+ if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1569
+ raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
1570
+ matches = worker.run(
1571
+ lambda: _network_summary(
1572
+ recorder,
1573
+ pattern=pattern,
1574
+ limit=entries,
1575
+ include_body=include_body,
1576
+ max_body_chars=body_chars,
1577
+ )
1578
+ )
1579
+ return {"sessionId": session_id, "count": len(matches), "matches": matches}
1580
+
1581
+
1582
+ def _state_path(args: dict[str, Any]) -> str:
1583
+ """解析会话状态文件的落点。
1584
+
1585
+ 目录**只从部署命名空间取**,因为这是**写文件**的能力:让模型选路径等于给它一个任意文件
1586
+ 写入口(写到某个被 source 的脚本里就够了)。模型只能给这个名字,且必须是那个目录下的
1587
+ 直接子项。
1588
+
1589
+ :param args: 协议参数
1590
+ :returns: 状态文件的绝对路径
1591
+ :raises AdapterError: 部署没配目录,或名字不是纯文件名
1592
+ """
1593
+ deployment = args.get("deployment")
1594
+ directory = deployment.get("sessionStateDir") if isinstance(deployment, dict) else None
1595
+ if not isinstance(directory, str) or not directory:
1596
+ raise AdapterError(
1597
+ "STATE_DISABLED",
1598
+ "this deployment has no sessionStateDir configured; browser login state cannot be saved or loaded",
1599
+ )
1600
+ name = args.get("name")
1601
+ if not isinstance(name, str) or not name:
1602
+ raise AdapterError("BAD_ARGS", "name is required")
1603
+ if name != Path(name).name or name.startswith("."):
1604
+ raise AdapterError("BAD_ARGS", f"name must be a plain file name, got {name!r}")
1605
+ return str(Path(directory) / f"{name}.json")
1606
+
1607
+
1608
+ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
1609
+ """存取浏览器会话的登录态。
1610
+
1611
+ 0.5 起上游提供 ``save_state`` / ``load_state``(Playwright 兼容的 JSON:cookie、
1612
+ localStorage、IndexedDB),于是「登录一次、下次复用」不必再让模型把站点爬两遍。
1613
+
1614
+ :param args: 协议参数
1615
+ :param saving: True 存、False 取
1616
+ :returns: 落点与结果
1617
+ :raises AdapterError: 会话不存在 / 静态会话没有浏览器状态 / 落点非法 / 上游报错
1618
+ """
1619
+ session_id = args.get("sessionId")
1620
+ entry = _get_session(session_id)
1621
+ if entry["type"] == "static":
1622
+ raise AdapterError("BAD_ARGS", "static sessions have no browser state")
1623
+ target = _state_path(args)
1624
+ worker: _SessionWorker | None = entry["worker"]
1625
+ if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1626
+ raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
1627
+ session = entry["session"]
1628
+ try:
1629
+ if saving:
1630
+ worker.run(lambda: session.save_state(target))
1631
+ else:
1632
+ worker.run(lambda: session.load_state(target))
1633
+ except Exception as error: # noqa: BLE001 —— 上游的文件/JSON 错误一律翻成可路由的码
1634
+ raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
1635
+ return {"sessionId": session_id, "path": target, "saved": saving}
1636
+
1637
+
1638
+ def session_state_save(args: dict[str, Any]) -> dict[str, Any]:
1639
+ """把会话的登录态存成一个文件。
1640
+
1641
+ :param args: 协议参数
1642
+ :returns: 落点与结果
1643
+ """
1644
+ return _session_state(args, saving=True)
1645
+
1646
+
1647
+ def session_state_load(args: dict[str, Any]) -> dict[str, Any]:
1648
+ """把一个状态文件载入会话(载入后要重新抓一次页面才用上它)。
1649
+
1650
+ :param args: 协议参数
1651
+ :returns: 落点与结果
1652
+ """
1653
+ return _session_state(args, saving=False)
1654
+
1655
+
1372
1656
  def close_all_sessions() -> None:
1373
1657
  """关掉全部会话。进程退出与 sidecar 重启时调用。
1374
1658
 
@@ -1387,6 +1671,9 @@ METHODS.update(
1387
1671
  "session.fetch": session_fetch,
1388
1672
  "session.list": session_list,
1389
1673
  "session.close": session_close,
1674
+ "session.network": session_network,
1675
+ "session.state_save": session_state_save,
1676
+ "session.state_load": session_state_load,
1390
1677
  }
1391
1678
  )
1392
1679
  METHODS.update(CRAWL_METHODS)