@jayyuen66/dsh-scrapling 0.0.2 → 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
 
@@ -477,6 +511,7 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
477
511
 
478
512
  :param args: 协议参数
479
513
  :returns: 归一后的载荷
514
+ :raises AdapterError: 方法不支持、部署未开放写方法,或抓取失败
480
515
  """
481
516
  _require(Fetcher)
482
517
  url = _url(args)
@@ -493,13 +528,34 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
493
528
  method = str(args.get("method", "GET")).upper()
494
529
  if method not in ("GET", "POST", "PUT", "DELETE"):
495
530
  raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
531
+ if method != "GET" and not guard.ALLOW_WRITE_METHODS:
532
+ # 这一侧是硬拒,不依赖 Host 有没有把入参摆出来:手搓一帧 stdin 也写不出去。
533
+ raise AdapterError(
534
+ "WRITE_DISABLED",
535
+ f"{method} changes state on the remote side; the deployment must set "
536
+ f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
537
+ )
496
538
  if method != "GET":
497
539
  body = args.get("body")
498
- if isinstance(body, dict):
499
- params["json"] = _jsonable(body)
500
- elif isinstance(body, str):
540
+ if isinstance(body, str):
501
541
  params["data"] = body
542
+ elif body is not None:
543
+ # 数组、数字、布尔也是合法的 JSON 请求体(curl_cffi 的 ``json=`` 照收)。此前只有
544
+ # dict 走 json、str 走 data,其余**静默丢弃** —— 模型发一个 `body: [1, 2]`,请求照
545
+ # 发、对端收到空体,而回包上没有一行能看出这件事。
546
+ params["json"] = _jsonable(body)
502
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}")
503
559
  response = getattr(Fetcher, method.lower())(url, **params)
504
560
  return to_payload(
505
561
  response,
@@ -511,30 +567,132 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
511
567
  )
512
568
 
513
569
 
514
- def _xhr_pattern(args: dict[str, Any]) -> str | None:
515
- """取 XHR 捕获正则,并确认它编译得过。
570
+ def _url_pattern(args: dict[str, Any]) -> str | None:
571
+ """取网络历史的 URL 过滤正则,并确认它编译得过。
516
572
 
517
- 这个串由 :mod:`scrapling` 塞进响应处理器,对**每个**响应跑一次 ``re.search``。
518
- 写错一个字符时若不在这里拦下,报错会发生在浏览器的事件回调里 —— 表现是「页面抓到了,
519
- 但整次抓取冒出一串看不懂的错」,而用户看不出根因是自己正则写错了。
573
+ 上游 ``NetworkRecorder.search`` 拿它做 ``re.compile``,编译不过会抛 ValueError;那一层
574
+ 报的是「Invalid URL pattern: ...」,读的人看不出根因是自己正则写错了。所以在读历史
575
+ 之前就地判。
520
576
 
521
577
  :param args: 协议参数
522
- :returns: 正则文本;没给或为空串时给 None(Scrapling 据此不捕获)
578
+ :returns: 正则文本;没给或为空串时给 None(上游据此不过滤)
523
579
  :raises AdapterError: 正则编译不过
524
580
  """
525
- raw = args.get("captureXhrPattern")
581
+ raw = args.get("urlPattern")
526
582
  if not isinstance(raw, str) or not raw:
527
583
  return None
528
584
  try:
529
585
  re.compile(raw)
530
586
  except re.error as error:
531
- 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
532
588
  return raw
533
589
 
534
590
 
535
- def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
591
+ # ``StealthySession.fetch`` 只认这份名单(上游 ``engines/_browsers/_validators.py`` 的
592
+ # ``_fetch_params`` 字段,外加实现自己 ``pop`` 出来的 ``proxy``)。名单之外的键**不报错、
593
+ # 不生效**:``validate_fetch`` 只从 kwargs 里挑认识的字段,其余原样丢掉。
594
+ #
595
+ # 所以会话路径上必须按层级分家:这些键在 fetch 层传了等于没传,唯一生效的地方是会话构造
596
+ # (``StealthySession(...)``)。``py/tests/contract_probe.py`` 会拿真实上游校验这张表与
597
+ # ``_fetch_params`` 是否仍然一致。
598
+ FETCH_LEVEL_KEYS = frozenset(
599
+ {
600
+ "blocked_domains",
601
+ "disable_resources",
602
+ "extra_headers",
603
+ "google_search",
604
+ "load_dom",
605
+ "network_idle",
606
+ "page_action",
607
+ "page_setup",
608
+ "pierce_shadow",
609
+ "proxy",
610
+ "selector_config",
611
+ "solve_cloudflare",
612
+ "timeout",
613
+ "wait",
614
+ "wait_selector",
615
+ "wait_selector_state",
616
+ }
617
+ )
618
+
619
+ # 只有会话构造才吃的那些键:从 fetch 层传过去必然被静默丢弃,因此要么在这里进会话,
620
+ # 要么就根本别发。
621
+ #
622
+ # 这张表是**上游的事实**而不是本包的透传清单:`max_pages` / `retries` / `retry_delay` 上游
623
+ # 确实是构造期参数,但本包一个都不发(各自没有对应的部署设置),所以它们在
624
+ # `_browser_params` 的产物里根本不出现 —— 过滤器对它们是无操作,留着是为了让
625
+ # `py/tests/contract_probe.py` 能拿整张表与上游字段面比对,而不是只比对我们用到的那几项。
626
+ #
627
+ # `record_requests` / `max_recorded_requests` 是 0.5 用会话网络历史替代 `capture_xhr` 之后
628
+ # 新增的两枚:它们**只**在构造期生效,逐次 fetch 传等于没传(这正是那个替代方案的核心)。
629
+ SESSION_ONLY_KEYS = frozenset(
630
+ {
631
+ "allow_webgl",
632
+ "block_ads",
633
+ "block_webrtc",
634
+ "cdp_url",
635
+ "dns_over_https",
636
+ "executable_path",
637
+ "headless",
638
+ "hide_canvas",
639
+ "init_script",
640
+ "locale",
641
+ "max_pages",
642
+ "max_recorded_requests",
643
+ "real_chrome",
644
+ "record_requests",
645
+ "retries",
646
+ "retry_delay",
647
+ "timezone_id",
648
+ "useragent",
649
+ "user_data_dir",
650
+ }
651
+ )
652
+
653
+
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]:
536
684
  """浏览器抓取的公共参数。
537
685
 
686
+ ``level`` 决定这份参数**送给哪一层**:一次性抓取(``StealthyFetcher.fetch``)与会话构造
687
+ 收的是完整的会话级参数面;而会话内每次 fetch 只认 ``FETCH_LEVEL_KEYS`` 那十几个键,其余
688
+ 一律被上游静默丢弃(见上面那张表的注释)。所以 ``level="fetch"`` 时按名单过滤 ——
689
+ 宁可少发一个键,也不要发一个「看起来在生效其实没生效」的键:后者的排查成本是整条链路。
690
+
691
+ WebRTC 防泄露只走 ``block_webrtc`` 开关本身。0.4.15 时代这里还要往启动参数里塞两条
692
+ flag,因为那时的 ``config.extra_flags`` 会**顶掉**内建那套反检测 flag;0.5 把它改成
693
+ 叠加(上游 PR #430),而浏览器抓取也只剩 patchright 一套,``block_webrtc`` 一条开关
694
+ 两件事都覆盖,于是那条绕行路径连同它要回避的坑一起消失。
695
+
538
696
  ``block_ads`` 由部署设置决定,可以打开:它并不会与 SSRF 守卫抢 handler。
539
697
  上游把 ``block_ads`` 折进**同一个** ``blocked_domains``(engines/_browsers/
540
698
  _validators.py),交给 engines/_browsers/_base.py 里那一个
@@ -545,12 +703,17 @@ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
545
703
  ``blocked_domains`` / ``disable_resources`` 仍固定关闭:本包没有对应的部署设置,
546
704
  而打开它们同样只是给上游那个 handler 加料,不会削弱守卫。
547
705
 
548
- 代理在这里显式交给引擎,是三条抓取路径里唯一必须这么做的一条:Chromium 不读
706
+ 代理在这里显式交给引擎,是浏览器这条路径上唯一必须这么做的地方:Chromium 不读
549
707
  ``HTTP_PROXY``/``ALL_PROXY``,只读系统代理设置,于是一台只在 shell 里 export 过代理
550
- 的机器上静态抓取走代理、浏览器抓取却直连。传 ``proxy`` 给 ``DynamicFetcher.fetch`` /
551
- ``StealthyFetcher.fetch`` 时它落进**会话**配置(fetchers/*.py 里是
552
- ``DynamicSession(**kwargs)``),进 ``launch_persistent_context`` 的 context 选项 ——
553
- 所以是一次抓取一个 context,与一次性会话的既有形态一致,且不会丢 cookie。
708
+ 的机器上静态抓取走代理、浏览器抓取却直连。传 ``proxy`` 给 ``StealthyFetcher.fetch``
709
+ 时它落进**会话**配置(fetchers/stealth_chrome.py 里是 ``StealthySession(**kwargs)``),
710
+ 进 ``launch_persistent_context`` 的 context 选项 —— 所以是一次抓取一个 context,
711
+ 与一次性会话的既有形态一致,且不会丢 cookie。
712
+
713
+ :param args: 协议参数
714
+ :param url: 本次抓取的地址,用来定代理
715
+ :param level: ``session``(会话级全量)或 ``fetch``(只发 fetch 层认得的键)
716
+ :returns: 引擎参数
554
717
  """
555
718
  params: dict[str, Any] = {
556
719
  "headless": bool(args.get("headless", True)),
@@ -562,10 +725,6 @@ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
562
725
  proxy = guard.browser_proxy(url)
563
726
  if proxy is not None:
564
727
  params["proxy"] = proxy
565
- # WebRTC 能绕过代理直接发 UDP,页面里一句 STUN 就能问出访客的真实出口 IP。
566
- # 走代理时那条信息本就不该泄露,所以两套引擎都上对应的开关:patchright 有
567
- # block_webrtc,Playwright 没有,只能用 Chromium 的启动 flag。
568
- params["extra_flags"] = [guard.WEBRTC_NO_LEAK_FLAG]
569
728
  if args.get("networkIdle"):
570
729
  params["network_idle"] = True
571
730
  for key, name in (
@@ -578,23 +737,15 @@ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
578
737
  value = args.get(key)
579
738
  if isinstance(value, str) and value:
580
739
  params[name] = value
581
- # XHR 捕获正则单独走一道:它是用户手写的正则,编译不过要在发车前就报出来,
582
- # 而不是等它在浏览器的事件回调里炸。
583
- xhr_pattern = _xhr_pattern(args)
584
- if xhr_pattern is not None:
585
- params["capture_xhr"] = xhr_pattern
586
- # 浏览器二进制路径与 CDP 端点只从 deployment 命名空间取,不在上面的模型可见透传表里:
587
- # executable_path 等于「让 Chromium 去执行这个文件」,cdp_url 等于「把浏览器交给这个
588
- # 调试端点」,两者都是部署级的强能力,但绝不能由模型入参驱动。Host 侧对应的两枚设置
589
- # 同样是非 volatile 的部署级字段(不进设置卡)。
740
+ # open shadow root 里的内容默认不进正文 —— 页面把那部分内容藏在 shadow 里时,
741
+ # 不打开这个开关在 HTML 里根本看不到它。
742
+ if args.get("pierceShadow"):
743
+ params["pierce_shadow"] = True
590
744
  deployment = args.get("deployment")
591
745
  if isinstance(deployment, dict):
592
- for source, target in (
593
- ("browserExecutablePath", "executable_path"),
594
- ("browserCdpUrl", "cdp_url"),
595
- ):
596
- value = deployment.get(source)
597
- 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:
598
749
  params[target] = value
599
750
  wait_ms = args.get("waitMs")
600
751
  if isinstance(wait_ms, (int, float)) and not isinstance(wait_ms, bool) and wait_ms > 0:
@@ -602,32 +753,53 @@ def _browser_params(args: dict[str, Any], url: str) -> dict[str, Any]:
602
753
  extra_headers = _string_map(args.get("extraHeaders"), "extraHeaders")
603
754
  if extra_headers is not None:
604
755
  params["extra_headers"] = extra_headers
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))
764
+ if level == "fetch":
765
+ return {key: value for key, value in params.items() if key in FETCH_LEVEL_KEYS}
605
766
  return params
606
767
 
607
768
 
608
- def render(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
609
- """浏览器抓取。``stealth`` 为真时走 patchright 引擎。
769
+ def _session_browser_params(args: dict[str, Any]) -> dict[str, Any]:
770
+ """会话构造期的浏览器参数:只收**只有开场才生效**的那些键。
771
+
772
+ 会话内每次 fetch 传 ``block_ads`` / ``record_requests`` / ``executable_path`` /
773
+ ``cdp_url`` / ``locale`` / ``timezone_id`` / ``useragent`` / ``headless`` 都会被
774
+ ``validate_fetch`` 丢掉,于是设置卡上这些旋钮对会话路径完全不生效 —— 而且不报错。
775
+ 这里把它们挪到唯一生效的位置。
776
+
777
+ 代理不在这张表里:会话的代理在开场时按 ``default_proxy()`` 定一次(中途换代理要新建
778
+ context,等于丢掉 cookie 与登录态,而那正是会话存在的理由),见 :func:`_make_session`。
779
+
780
+ :param args: 协议参数
781
+ :returns: 会话构造参数
782
+ """
783
+ # url 只用来定代理,而会话级代理另在 _make_session 里定,这里给空串即可。
784
+ full = _browser_params(args, "")
785
+ # timeout 在两层都认,会话构造必须带上它,否则整个会话回落到上游的 30s 页面超时。
786
+ keep = SESSION_ONLY_KEYS | {"timeout"}
787
+ return {key: value for key, value in full.items() if key in keep}
788
+
789
+
790
+ def render(args: dict[str, Any]) -> dict[str, Any]:
791
+ """浏览器抓取(patchright)。0.5 起这是唯一的浏览器引擎。
610
792
 
611
793
  :param args: 协议参数
612
- :param stealth: 是否用 StealthyFetcher
613
794
  :returns: 归一后的载荷
614
795
  """
615
- engine = StealthyFetcher if stealth else DynamicFetcher
616
- _require(engine)
796
+ _require(StealthyFetcher)
617
797
  url = _url(args)
618
798
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
619
799
 
620
800
  params = _browser_params(args, url)
621
801
  params["page_setup"] = page_setup
622
- if stealth:
623
- params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
624
- params["hide_canvas"] = bool(args.get("hideCanvas", False))
625
- # 走代理时强制为真,不看模型入参:WebRTC 泄露的是访客的真实出口 IP,而访客用这个
626
- # 插件正是为了不泄露它。
627
- params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or "proxy" in params
628
- params["allow_webgl"] = bool(args.get("allowWebgl", True))
629
-
630
- response = engine.fetch(url, **params)
802
+ response = StealthyFetcher.fetch(url, **params)
631
803
  return to_payload(
632
804
  response,
633
805
  extraction_type=extraction_type,
@@ -638,6 +810,114 @@ def render(args: dict[str, Any], *, stealth: bool) -> dict[str, Any]:
638
810
  )
639
811
 
640
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
+
641
921
  def _fake_response(html: str, url: str, status: int) -> Any:
642
922
  """造一个不带网络的 ``Response``,给离线抽取用。"""
643
923
  from scrapling.engines.toolbelt.custom import Response
@@ -786,15 +1066,15 @@ def _scrapling_version() -> str:
786
1066
  def _probe_browser(module_name: str) -> bool:
787
1067
  """起一次浏览器再关掉,确认浏览器二进制真的可用。
788
1068
 
789
- 为什么直接用 Playwright/patchright 而不走 ``engine.fetch``:Scrapling 的 fetch 会在
790
- ``page.goto`` 返回 None 时抛 "Failed to get response",而 ``data:`` 与 ``about:blank``
791
- 这类 URL 恰好不产生 response。拿它们当探针 URL 会稳定地假失败,还会被 ``retries``
792
- 放大成几秒钟的重试风暴。
1069
+ 为什么直接用引擎而不走 ``engine.fetch``:Scrapling 的 fetch 会在 ``page.goto`` 返回
1070
+ None 时抛 "Failed to get response",而 ``data:`` 与 ``about:blank`` 这类 URL 恰好不
1071
+ 产生 response。拿它们当探针 URL 会稳定地假失败,还会被 ``retries`` 放大成几秒钟的重试
1072
+ 风暴。
793
1073
 
794
- 要验的其实只有一件事:**浏览器二进制装没装**。``playwright install chromium`` 与
795
- patchright 各自管理浏览器,少任一个都会在真正调用时才炸,所以两个引擎都要单独探。
1074
+ 要验的其实只有一件事:**浏览器二进制装没装**。``patchright install chromium`` 装的是
1075
+ patchright 自己那一份,缺了它会在真正调用时才炸。
796
1076
 
797
- :param module_name - ``"playwright.sync_api"`` 或 ``"patchright.sync_api"``
1077
+ :param module_name - 要探的引擎模块名,目前只有 ``"patchright.sync_api"``
798
1078
  :returns: 浏览器能否启动
799
1079
  """
800
1080
  import importlib
@@ -816,13 +1096,16 @@ def capabilities() -> dict[str, Any]:
816
1096
  "static": SCRAPLING_AVAILABLE,
817
1097
  "extract": SCRAPLING_AVAILABLE,
818
1098
  "browser": False,
819
- "stealth": False,
1099
+ # 写方法这一档**与 scrapling 在不在无关**:它是部署表态,而排障的人得能一眼看出
1100
+ # 「这台到底许不许写」,而不是等到发 POST 被拒才发现环境里少一个变量。
1101
+ "writeMethods": guard.ALLOW_WRITE_METHODS,
820
1102
  }
821
1103
  if not SCRAPLING_AVAILABLE:
822
1104
  return report
823
1105
  report["version"] = _scrapling_version()
824
- report["browser"] = _probe_browser("playwright.sync_api")
825
- report["stealth"] = _probe_browser("patchright.sync_api")
1106
+ # 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
1107
+ # 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的口径已经没有第二个引擎可标。
1108
+ report["browser"] = _probe_browser("patchright.sync_api")
826
1109
  # 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
827
1110
  # server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
828
1111
  report["proxy"] = guard.proxy_settings()
@@ -833,8 +1116,8 @@ METHODS = {
833
1116
  "ping": lambda _args: {"pong": True},
834
1117
  "capabilities": lambda _args: capabilities(),
835
1118
  "fetch": fetch,
836
- "render": lambda args: render(args, stealth=False),
837
- "stealth_fetch": lambda args: render(args, stealth=True),
1119
+ "render": render,
1120
+ "capture": capture,
838
1121
  "extract": extract,
839
1122
  "select": select,
840
1123
  }
@@ -847,18 +1130,19 @@ METHODS = {
847
1130
  # 会话把这份状态留在 sidecar 进程里跨请求复用 —— 这是 Scrapling 相对
848
1131
  # 「每次调用都重新来」最实用的一块。
849
1132
  #
850
- # 三种类型与 Scrapling 的一一对应:
1133
+ # 两种类型与 Scrapling 的一一对应:
851
1134
  # static -> FetcherSession(curl_cffi)
852
- # browser -> DynamicSession(Playwright)
853
- # stealth -> StealthySession(patchright)
1135
+ # stealth -> StealthySession(patchright,0.5 起唯一的浏览器引擎)
854
1136
  # ---------------------------------------------------------------------------
855
1137
 
856
1138
  _SESSION_CLASSES = {
857
1139
  "static": "FetcherSession",
858
- "browser": "DynamicSession",
859
1140
  "stealth": "StealthySession",
860
1141
  }
861
1142
 
1143
+ # 吃内存的那几类(每个都是一个真实浏览器进程):名额与专属执行线程都按它判。
1144
+ _BROWSER_KINDS = frozenset({"stealth"})
1145
+
862
1146
  # 会话注册表。sidecar 是常驻进程,这里就是它的内存;进程退出时全部随之消失。
863
1147
  # 值里存 {"session": <对象>, "type": <str>, "created_at": <iso8601>, "lock": Lock,
864
1148
  # "worker": _SessionWorker | None};正在构造中的条目只有
@@ -872,11 +1156,11 @@ _SESSIONS: dict[str, dict[str, Any]] = {}
872
1156
  # 跑的 Chromium),名额判完再开等于没判。
873
1157
  _SESSION_LOCK = threading.Lock()
874
1158
 
875
- # 同开几个会话。browser/stealth 每开一个就是一个真实的 Chromium 进程,而 sessionType 是
1159
+ # 同开几个会话。浏览器会话每开一个就是一个真实的 Chromium 进程,而 sessionType 是
876
1160
  # **模型可选**的参数 —— 不设上限的话,「开 → 不关」重复几次就能把机器的内存吃光。
877
1161
  # 因此在登记之前就判,而不是指望模型记得调 session_close。
878
1162
  MAX_SESSIONS = 8
879
- # 其中最多几个可以是吃内存的那两种。static 只是连接池,便宜得多。
1163
+ # 其中最多几个可以是吃内存的浏览器会话。static 只是连接池,便宜得多。
880
1164
  MAX_BROWSER_SESSIONS = 3
881
1165
 
882
1166
 
@@ -967,27 +1251,32 @@ def _make_session(kind: str, args: dict[str, Any]) -> Any:
967
1251
  # wrapper 要留在登记条目里,close 时才能 __exit__。
968
1252
  return logic, wrapper
969
1253
 
970
- from scrapling.fetchers import DynamicSession, StealthySession
1254
+ from scrapling.fetchers import StealthySession
971
1255
 
972
- headless = bool(args.get("headless", True))
973
- timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
974
- common: dict[str, Any] = {"headless": headless, "timeout": timeout_ms}
1256
+ # 只有开场才生效的那些设置(block_ads / record_requests / headless / locale /
1257
+ # timezone_id / useragent / executable_path / cdp_url / timeout)必须在这里进会话:
1258
+ # fetch 层传过去会被 validate_fetch 静默丢掉(见 FETCH_LEVEL_KEYS)。
1259
+ common: dict[str, Any] = _session_browser_params(args)
1260
+ # 每会话的记录开关:模型可以为这一次会话打开记录(部署侧那枚是默认值)。记录不改变
1261
+ # 请求行为,只是把已经发生的流量留在内存里,所以它不是部署级强能力。
1262
+ if args.get("recordNetwork") is True:
1263
+ common["record_requests"] = True
975
1264
  # 会话开的时候还不知道要访问哪个主机,所以按「配了代理就用代理」定档;显式填过
976
1265
  # proxyBypass 的主机在会话里也跟着走代理 —— 见上面的取舍说明。
977
1266
  proxy = guard.split_proxy(guard.default_proxy())
978
1267
  if proxy is not None:
979
1268
  common["proxy"] = proxy
980
- common["extra_flags"] = [guard.WEBRTC_NO_LEAK_FLAG]
981
- if kind == "browser":
982
- session: DynamicSession | StealthySession = DynamicSession(**common)
983
- else:
984
- session = StealthySession(
985
- **common,
986
- solve_cloudflare=bool(args.get("solveCloudflare", False)),
987
- hide_canvas=bool(args.get("hideCanvas", False)),
988
- block_webrtc=bool(args.get("blockWebrtc", False)) or proxy is not None,
989
- allow_webgl=bool(args.get("allowWebgl", True)),
990
- )
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)
991
1280
  session.start()
992
1281
  return session, session
993
1282
 
@@ -1009,8 +1298,8 @@ def _enforce_session_limits(kind: str) -> None:
1009
1298
  f"{len(_SESSIONS)} sessions are already open (limit {MAX_SESSIONS}); "
1010
1299
  "close one with session.close before opening another",
1011
1300
  )
1012
- if kind in ("browser", "stealth"):
1013
- 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)
1014
1303
  if browsers >= MAX_BROWSER_SESSIONS:
1015
1304
  raise AdapterError(
1016
1305
  "SESSION_LIMIT",
@@ -1068,8 +1357,6 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1068
1357
  "session": usable, # 真正发请求的对象
1069
1358
  "closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
1070
1359
  "type": kind,
1071
- # 浏览器会话是否带着代理;stealth 的 block_webrtc 要在每次 fetch 时跟着它走。
1072
- "proxied": kind != "static" and guard.default_proxy() != "",
1073
1360
  "created_at": datetime.now(timezone.utc).isoformat(),
1074
1361
  # 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
1075
1362
  "lock": entry_lock,
@@ -1110,37 +1397,57 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1110
1397
 
1111
1398
  :param args: 协议参数
1112
1399
  :returns: 归一后的载荷
1113
- :raises AdapterError: 会话不存在 / 类型不支持 / 抓取失败
1400
+ :raises AdapterError: 会话不存在 / 类型不支持 / 抓取失败 / 把 static 专属的键给了浏览器会话
1114
1401
  """
1115
1402
  entry = _get_session(args.get("sessionId"))
1116
1403
  session = entry["session"]
1117
1404
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
1118
1405
  url = _url(args)
1119
1406
 
1120
- # 一份会话同一时刻只服务一个请求:static 靠 entry 锁,browser/stealth 靠属主线程
1121
- # 天然串行。两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步
1122
- # API 靠 greenlet 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个
1123
- # 会话」。表现是看不懂的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
1407
+ # 一份会话同一时刻只服务一个请求:static 靠 entry 锁,浏览器会话靠属主线程天然串行。
1408
+ # 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
1409
+ # 一次只服务一个线程,curl_cffi 的 Session 文档原话是「一个时刻一个会话」。表现是看不懂
1410
+ # 的崩溃,甚至是上下文串台 —— 所以在结构上就不给这个可能。
1124
1411
  try:
1125
1412
  if entry["type"] == "static":
1126
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}")
1127
1419
  response = session.get(url, **_static_params(args, url))
1128
1420
  else:
1129
1421
  # 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
1130
1422
  # 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
1131
- params = _browser_params(args, url)
1423
+ #
1424
+ # level="fetch" 是这条路径的关键:会话内每次 fetch 只认 FETCH_LEVEL_KEYS,
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")
1132
1431
  params.pop("proxy", None)
1133
- params.pop("extra_flags", None)
1134
1432
  params["page_setup"] = page_setup
1135
- if entry["type"] == "stealth":
1136
- params["solve_cloudflare"] = bool(args.get("solveCloudflare", False))
1137
- params["hide_canvas"] = bool(args.get("hideCanvas", False))
1138
- params["block_webrtc"] = bool(args.get("blockWebrtc", False)) or bool(entry["proxied"])
1139
- params["allow_webgl"] = bool(args.get("allowWebgl", True))
1433
+ # headers / retries 只有 static 那条路读得懂(_static_params):浏览器会话的请求头
1434
+ # 是 extra_headers,重试则是会话构造期的 config.retries。传错了不生效,而上游连
1435
+ # 一声都不抱怨 —— 这里替它抱怨,因为「拧了没反应」正是本包在消灭的那类故障,而
1436
+ # 一句 "use extraHeaders" 是模型自己能纠正的。判在参数算完之后再抛:那个顺序让
1437
+ # py/tests/contract_probe.py 的读取记录保持完整(它按「读过哪些键」出结论)。
1438
+ #
1439
+ # 空的没给(`{}` / `[]` / null)不算写意图:模型「不带任何请求头」时传的就是空表,
1440
+ # 为它报一条错等于把一个无害的调用说成非法。
1441
+ for key, hint in (("headers", "extraHeaders"), ("retries", "scrapling_session_open")):
1442
+ if args.get(key) not in (None, {}, []):
1443
+ raise AdapterError(
1444
+ "BAD_ARGS",
1445
+ f"{key} only applies to static sessions; use {hint} for a {entry['type']} session",
1446
+ )
1140
1447
  # 投递到属主线程执行:greenlet 绑定在那里(见 _SessionWorker)。排队期间调用
1141
1448
  # 线程原地等 —— 并发的 fetch 因此天然串行,entry 锁对浏览器会话是多余的。
1142
1449
  worker: _SessionWorker | None = entry["worker"]
1143
- if worker is None: # pragma: no cover —— browser/stealth 条目必有属主线程
1450
+ if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1144
1451
  raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
1145
1452
  response = worker.run(lambda: session.fetch(url, **params))
1146
1453
  except AdapterError:
@@ -1233,6 +1540,119 @@ def session_close(args: dict[str, Any]) -> dict[str, Any]:
1233
1540
  return {"sessionId": session_id, "closed": True}
1234
1541
 
1235
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
+
1236
1656
  def close_all_sessions() -> None:
1237
1657
  """关掉全部会话。进程退出与 sidecar 重启时调用。
1238
1658
 
@@ -1251,6 +1671,9 @@ METHODS.update(
1251
1671
  "session.fetch": session_fetch,
1252
1672
  "session.list": session_list,
1253
1673
  "session.close": session_close,
1674
+ "session.network": session_network,
1675
+ "session.state_save": session_state_save,
1676
+ "session.state_load": session_state_load,
1254
1677
  }
1255
1678
  )
1256
1679
  METHODS.update(CRAWL_METHODS)