@jayyuen66/dsh-scrapling 0.0.3 → 0.1.1

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