@jayyuen66/dsh-scrapling 0.1.1 → 0.1.3

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/crawl.py CHANGED
@@ -11,6 +11,8 @@ daemon 线程**跑 spider,主线程立刻返回 crawl id;进度通过「没
11
11
  from __future__ import annotations
12
12
 
13
13
  import json
14
+ import re
15
+ import sys
14
16
  import threading
15
17
  import time
16
18
  import uuid
@@ -36,6 +38,10 @@ MAX_CONCURRENT_CRAWLS = 2
36
38
  # 结束就删;但全留着就是内存泄漏,所以留一个上限,按最旧的淘汰。
37
39
  MAX_REMEMBERED_CRAWLS = 16
38
40
 
41
+ # sidecar 收尾时给每只蜘蛛的等待预算(秒)。宿主那边的优雅关闭只有 sidecarGraceMs(默认
42
+ # 5s)那么久,超了就把进程杀掉;这里必须比它小,否则「等蜘蛛停」自己会变成关机卡住的原因。
43
+ SHUTDOWN_JOIN_SECONDS = 2.0
44
+
39
45
  # 一次 crawl.status 回包的字节上界。Host 侧按 8 MiB 切帧,而一个快站点能在一个轮询间隔里
40
46
  # 落下几十页;留一半余量,越过切帧线的那一帧会把整个 sidecar 拆掉。回不完的由 `more` 交接。
41
47
  MAX_STATUS_BYTES = 4 * 1024 * 1024
@@ -49,6 +55,26 @@ DEFAULT_MAX_RUNTIME_MS = 1_800_000
49
55
  # 日志里不是同一件事。
50
56
  DEFAULT_CONCURRENT_REQUESTS = 4
51
57
 
58
+ # 只投影这些统计字段:上游 to_dict() 还带 autothrottle / log_count / proxies 等
59
+ # 部署内部读数,模型用不上,也不该成为协议面的一部分。
60
+ _STATS_KEYS = (
61
+ "requests_count",
62
+ "failed_requests_count",
63
+ "blocked_requests_count",
64
+ "offsite_requests_count",
65
+ "robots_disallowed_count",
66
+ "items_scraped",
67
+ "elapsed_seconds",
68
+ "response_bytes",
69
+ "response_status_count",
70
+ )
71
+
72
+
73
+ def _stats_projection(stats: Any) -> dict[str, Any]:
74
+ """把 ``CrawlStats`` 压成协议声明的子集。"""
75
+ data = stats.to_dict()
76
+ return {key: data[key] for key in _STATS_KEYS if key in data}
77
+
52
78
 
53
79
  def _crawl_policy(args: dict[str, Any]) -> dict[str, Any]:
54
80
  """读部署命名空间里的爬虫策略旋钮。
@@ -146,6 +172,127 @@ def _within_allowed_domains(url: str, allowed: set[str]) -> bool:
146
172
  return any(domain == entry or domain.endswith(f".{entry}") for entry in allowed)
147
173
 
148
174
 
175
+ def _crawl_patterns(value: Any, field: str) -> list[str]:
176
+ """校验并编译 crawl 的 include/exclude 正则。"""
177
+ from adapters import AdapterError
178
+
179
+ if value is None:
180
+ return []
181
+ if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value):
182
+ raise AdapterError("BAD_ARGS", f"{field} must be an array of non-empty strings")
183
+ for pattern in value:
184
+ try:
185
+ re.compile(pattern)
186
+ except re.error as error:
187
+ raise AdapterError("BAD_ARGS", f"invalid crawl pattern: {error}") from error
188
+ return value
189
+
190
+
191
+ def _collect_page(
192
+ item: dict[str, Any],
193
+ *,
194
+ state: dict[str, Any],
195
+ limit: int,
196
+ crawl_id: str,
197
+ domains: set[str],
198
+ pause: Any,
199
+ ) -> None:
200
+ """收一页:域内/截止/清洗/封顶,与 content 模式同一条判据。"""
201
+ pages: list[dict[str, Any]] = state["pages"]
202
+ if len(pages) >= limit:
203
+ return
204
+ page_url = str(item.get("url", ""))
205
+ allowed, reason = url_allowed(page_url)
206
+ if allowed and not _within_allowed_domains(page_url, domains):
207
+ allowed, reason = False, "left the start domain (redirect)"
208
+ if not allowed:
209
+ _emit_event("crawlSkipped", crawlId=crawl_id, url=page_url, text=f"skipped {page_url}: {reason}")
210
+ return
211
+ if time.monotonic() >= state["deadline"]:
212
+ state["expired"] = True
213
+ _emit_event(
214
+ "crawlSkipped",
215
+ crawlId=crawl_id,
216
+ url=page_url,
217
+ text=f"crawl stopped: runtime budget of {state['budget_ms']}ms reached",
218
+ )
219
+ with suppress(RuntimeError):
220
+ pause()
221
+ return
222
+ markdown = str(item.get("markdown", ""))
223
+ if state["strip_inline_images"]:
224
+ from adapters import drop_data_uris
225
+
226
+ markdown = drop_data_uris(markdown)
227
+ pages.append(
228
+ {
229
+ "url": page_url,
230
+ "title": str(item.get("title", "")),
231
+ "markdown": _clip_markdown(markdown, state["max_content_chars"]),
232
+ }
233
+ )
234
+ _emit_event(
235
+ "progress",
236
+ crawlId=crawl_id,
237
+ done=len(pages),
238
+ limit=limit,
239
+ text=f"{len(pages)}/{limit} {page_url}",
240
+ )
241
+
242
+
243
+ def _collect_row(
244
+ item: dict[str, Any],
245
+ *,
246
+ state: dict[str, Any],
247
+ limit: int,
248
+ crawl_id: str,
249
+ pause: Any,
250
+ ) -> None:
251
+ """收一行结构化 feed 数据;行本身不再发请求,因此只受页数/时长约束。
252
+
253
+ 到点时必须像 :func:`_collect_page` 一样把 Spider 叫停:只置 ``expired`` 的话 spider
254
+ 会继续翻页,``maxDurationMs`` 对 feed / shopify 这两种模式等于没生效。
255
+ """
256
+ rows: list[dict[str, Any]] = state["rows"]
257
+ if len(rows) >= limit:
258
+ return
259
+ if time.monotonic() >= state["deadline"]:
260
+ state["expired"] = True
261
+ with suppress(RuntimeError):
262
+ pause()
263
+ return
264
+ rows.append(dict(item))
265
+ _emit_event(
266
+ "progress",
267
+ crawlId=crawl_id,
268
+ done=len(rows),
269
+ limit=limit,
270
+ text=f"{len(rows)}/{limit} row",
271
+ )
272
+
273
+
274
+ def _session_config(manager: Any, url: str) -> None:
275
+ """给爬虫换一份安全重定向 + 部署代理的静态会话。"""
276
+ from scrapling.fetchers import FetcherSession
277
+
278
+ session_kwargs: dict[str, Any] = {"follow_redirects": "safe"}
279
+ proxies = proxies_for(url)
280
+ if proxies is not None:
281
+ session_kwargs["proxies"] = proxies
282
+ manager.add("default", FetcherSession(**session_kwargs))
283
+
284
+
285
+ def _policy_attrs(policy: dict[str, Any]) -> dict[str, Any]:
286
+ """Spider 类属性上的待站策略(三种模板共用同一份)。"""
287
+ return {
288
+ "robots_txt_obey": policy["obey_robots"],
289
+ "download_delay": policy["delay_seconds"],
290
+ "concurrent_requests": policy["concurrency"],
291
+ "crawl_strategy": policy["strategy"],
292
+ "autothrottle_enabled": policy["autothrottle"],
293
+ }
294
+
295
+
149
296
  def _make_spider(
150
297
  url: str,
151
298
  limit: int,
@@ -153,6 +300,7 @@ def _make_spider(
153
300
  state: dict[str, Any],
154
301
  domains: set[str],
155
302
  policy: dict[str, Any],
303
+ options: dict[str, Any] | None = None,
156
304
  ) -> Any:
157
305
  """动态造一个 spider 类。
158
306
 
@@ -169,9 +317,15 @@ def _make_spider(
169
317
  :param policy: ``_crawl_policy`` 读出的待站策略
170
318
  :returns: spider 实例
171
319
  """
172
- from scrapling.spiders import SiteToMarkdownSpider
320
+ from scrapling.spiders import ContentSpider, CrawlRule, LinkExtractor
321
+
322
+ settings = options or {}
323
+ content_selector = settings.get("css_selector")
324
+ content_body_only = settings.get("main_content_only", True)
325
+ include_patterns = settings.get("include_patterns") or []
326
+ exclude_patterns = settings.get("exclude_patterns") or []
173
327
 
174
- class Collector(SiteToMarkdownSpider): # type: ignore[misc, valid-type]
328
+ class Collector(ContentSpider):
175
329
  """把页面攒进 state 并向上报进度,不落盘。"""
176
330
 
177
331
  name = f"scrapling-{crawl_id}"
@@ -179,14 +333,28 @@ def _make_spider(
179
333
  allowed_domains = domains
180
334
  max_pages = limit
181
335
  output_dir = None
182
- # 待站策略。robots_txt_obey 打开后 0.5 会把「取不到 robots.txt」当成禁止爬该域
183
- # (0.4.15 是放行),所以这一档要么别开,要么确保那台站点的 robots.txt 取得回来。
336
+ css_selector = content_selector
337
+ main_content_only = content_body_only
338
+ # 待站策略。robots_txt_obey 打开后 0.5 的取数口径是:抓取异常或 5xx → 该域按
339
+ # 全面禁止处理;站点没有 robots.txt(404)→ 视作允许全部。所以这一档要么别开,
340
+ # 要么确认目标站点 robots.txt 取得回来。
184
341
  robots_txt_obey = policy["obey_robots"]
185
342
  download_delay = policy["delay_seconds"]
186
343
  concurrent_requests = policy["concurrency"]
187
344
  crawl_strategy = policy["strategy"]
188
345
  autothrottle_enabled = policy["autothrottle"]
189
346
 
347
+ def rules(self) -> list[Any]:
348
+ """按模型给的 allow/deny 收窄链接发现;没给就沿用默认。"""
349
+ return [
350
+ CrawlRule(
351
+ LinkExtractor(
352
+ allow=include_patterns or (),
353
+ deny=exclude_patterns or (),
354
+ )
355
+ )
356
+ ]
357
+
190
358
  def configure_sessions(self, manager: Any) -> None:
191
359
  """把爬虫的会话换成「只跟安全重定向、走配置里那份代理」的那一份。
192
360
 
@@ -221,68 +389,212 @@ def _make_spider(
221
389
  :param item: spider 交来的页面
222
390
  :returns: 恒为 None
223
391
  """
224
- pages: list[dict[str, Any]] = state["pages"]
225
- if len(pages) >= limit:
226
- return None
227
- page_url = str(item.get("url", ""))
228
- # 收页前的最后两道:
229
- # 一是即使 safe 重定向放行了,这一页的最终 URL 仍可能落在私网上;
230
- # 二是它可能被重定向去了**站外另一台公网主机** —— allowed_domains 只参与链接
231
- # 发现,拦不住 curl_cffi 自己跟的那一跳。判否就不收:内容已经在对端取过了,
232
- # 但至少不把它写进 state 流回模型上下文。
233
- allowed, reason = url_allowed(page_url)
234
- if allowed and not _within_allowed_domains(page_url, domains):
235
- allowed, reason = False, "left the start domain (redirect)"
236
- if not allowed:
237
- _emit_event(
238
- "crawlSkipped",
239
- crawlId=crawl_id,
240
- url=page_url,
241
- text=f"skipped {page_url}: {reason}",
242
- )
243
- return None
244
- # 整体截止:页数上限管不了慢站点,而爬虫跑在没人看的后台线程里。到了点就按
245
- # 引擎自己的停机通道退场 —— pause() 让引擎在在途请求收尾后停,不是撕进程。
246
- if time.monotonic() >= state["deadline"]:
247
- state["expired"] = True
248
- _emit_event(
249
- "crawlSkipped",
250
- crawlId=crawl_id,
251
- url=page_url,
252
- text=f"crawl stopped: runtime budget of {state['budget_ms']}ms reached",
253
- )
254
- with suppress(RuntimeError):
255
- self.pause()
256
- return None
257
- markdown = str(item.get("markdown", ""))
258
- # 与其余抓取路径同一口径:内嵌 base64 图片是纯 token 噪音,先剥再封顶 ——
259
- # 顺序反了等于白剥,那几十 KB 早就把 max_content_chars 的额度吃掉了。
260
- if state["strip_inline_images"]:
261
- # 函数内导入:本模块顶层已经被 adapters 导入过,再顶层反向导入会成环
262
- # (adapters 末尾就是 `from crawl import METHODS`)。谁先被 import 决定
263
- # 这个环会不会炸,所以不赌。
264
- from adapters import drop_data_uris
265
-
266
- markdown = drop_data_uris(markdown)
267
- pages.append(
268
- {
269
- "url": page_url,
270
- "title": str(item.get("title", "")),
271
- "markdown": _clip_markdown(markdown, state["max_content_chars"]),
272
- }
392
+ _collect_page(
393
+ item,
394
+ state=state,
395
+ limit=limit,
396
+ crawl_id=crawl_id,
397
+ domains=domains,
398
+ pause=self.pause,
273
399
  )
274
- _emit_event(
275
- "progress",
276
- crawlId=crawl_id,
277
- done=len(pages),
400
+ return None
401
+
402
+ return Collector(crawldir=policy["checkpoint_dir"] or None)
403
+
404
+
405
+ def _make_sitemap_spider(
406
+ url: str,
407
+ limit: int,
408
+ crawl_id: str,
409
+ state: dict[str, Any],
410
+ domains: set[str],
411
+ policy: dict[str, Any],
412
+ options: dict[str, Any],
413
+ ) -> Any:
414
+ """SitemapSpider:只抓 sitemap 里的 loc,不跟随页面内链接。
415
+
416
+ ``max_pages`` / ``css_selector`` / ``main_content_only`` 不是上游 SitemapSpider 声明的类
417
+ 属性(content 模式那一支才认这三个),引擎读不到它们;页数上限与正文范围由下面那个
418
+ ``parse`` 自己取,别把它们当成引擎会执行的旋钮。
419
+ """
420
+ from scrapling.spiders import CrawlRule, LinkExtractor, SitemapSpider
421
+
422
+ include = options["include_patterns"]
423
+ exclude = options["exclude_patterns"]
424
+ follow = options["sitemap_follow"]
425
+ content_selector = options["css_selector"]
426
+ body_only = options["main_content_only"]
427
+
428
+ class Collector(SitemapSpider):
429
+ name = f"scrapling-{crawl_id}"
430
+ sitemap_urls = [options["sitemap_url"]]
431
+ sitemap_follow = LinkExtractor(allow=follow) if follow else None
432
+ allowed_domains = domains
433
+ max_pages = limit
434
+ css_selector = content_selector
435
+ main_content_only = body_only
436
+ robots_txt_obey = policy["obey_robots"]
437
+ download_delay = policy["delay_seconds"]
438
+ concurrent_requests = policy["concurrency"]
439
+ crawl_strategy = policy["strategy"]
440
+ autothrottle_enabled = policy["autothrottle"]
441
+
442
+ def rules(self) -> list[Any]:
443
+ if not include and not exclude:
444
+ return []
445
+ return [
446
+ CrawlRule(
447
+ LinkExtractor(allow=include or (), deny=exclude or ()),
448
+ callback=self.parse,
449
+ )
450
+ ]
451
+
452
+ def configure_sessions(self, manager: Any) -> None:
453
+ _session_config(manager, url)
454
+
455
+ async def parse(self, response: Any) -> Any:
456
+ if self.max_pages and len(state["pages"]) >= self.max_pages:
457
+ return
458
+ yield {
459
+ "url": response.url,
460
+ "title": str(response.css("title::text").get() or "").strip(),
461
+ "markdown": response.markdown(self.css_selector, self.main_content_only),
462
+ }
463
+
464
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
465
+ _collect_page(
466
+ item,
467
+ state=state,
278
468
  limit=limit,
279
- text=f"{len(pages)}/{limit} {page_url}",
469
+ crawl_id=crawl_id,
470
+ domains=domains,
471
+ pause=self.pause,
280
472
  )
281
473
  return None
282
474
 
283
475
  return Collector(crawldir=policy["checkpoint_dir"] or None)
284
476
 
285
477
 
478
+ def _make_shopify_spider(
479
+ url: str,
480
+ limit: int,
481
+ crawl_id: str,
482
+ state: dict[str, Any],
483
+ domains: set[str],
484
+ policy: dict[str, Any],
485
+ options: dict[str, Any],
486
+ ) -> Any:
487
+ """ShopifySpider:走 `/collections.json` 与每个集合的 `/products.json`,按变体出行。
488
+
489
+ 上游模板把三个 URL 写死成 `https://`,而本地夹具与内网镜像常常是 http;这里按起始
490
+ URL(或 `sitemapUrl`)的 scheme 重写同一组模板,好让「同一个实现」既能打真店也能打夹具。
491
+ """
492
+ from urllib.parse import urlsplit
493
+
494
+ from scrapling.spiders import ShopifySpider
495
+
496
+ override = options.get("sitemap_url")
497
+ if override is not None and (not isinstance(override, str) or not override):
498
+ from adapters import AdapterError
499
+
500
+ raise AdapterError("BAD_ARGS", "sitemapUrl must be a non-empty string or null")
501
+ source = override or url
502
+ parts = urlsplit(source)
503
+ scheme = parts.scheme or "https"
504
+ website = parts.netloc
505
+ if not website:
506
+ raise ValueError("shopify mode needs a host in url or sitemapUrl")
507
+
508
+ class Collector(ShopifySpider):
509
+ name = f"scrapling-{crawl_id}"
510
+ target_website = website
511
+ collections_url = f"{scheme}://{{website}}/collections.json?page={{page}}&limit=250"
512
+ products_url = f"{scheme}://{{website}}/collections/{{handle}}/products.json?page={{page}}&limit=250"
513
+ product_url = f"{scheme}://{{website}}/collections/{{handle}}/products/{{product_handle}}"
514
+ allowed_domains = domains
515
+ robots_txt_obey = policy["obey_robots"]
516
+ download_delay = policy["delay_seconds"]
517
+ concurrent_requests = policy["concurrency"]
518
+ autothrottle_enabled = policy["autothrottle"]
519
+
520
+ def configure_sessions(self, manager: Any) -> None:
521
+ # 代理判定跟着**真正要打的主机**走:shopify 的 collections/products 是用
522
+ # sitemapUrl(或 url)的 netloc 拼出来的,与 url 可能不是同一台。
523
+ _session_config(manager, source)
524
+
525
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
526
+ _collect_row(item, state=state, limit=limit, crawl_id=crawl_id, pause=self.pause)
527
+ if len(state["rows"]) >= limit:
528
+ # 集合分页对真店是有限的,但没有上限的目录会让作业一直跑下去;到量就叫停。
529
+ with suppress(RuntimeError):
530
+ self.pause()
531
+ return None
532
+
533
+ return Collector(crawldir=policy["checkpoint_dir"] or None)
534
+
535
+
536
+ def _make_feed_spider(
537
+ url: str,
538
+ limit: int,
539
+ crawl_id: str,
540
+ state: dict[str, Any],
541
+ domains: set[str],
542
+ policy: dict[str, Any],
543
+ options: dict[str, Any],
544
+ ) -> Any:
545
+ """XMLFeedSpider / CSVFeedSpider:按 fields 映射出行,不抓页面。"""
546
+ from scrapling.spiders import CSVFeedSpider, XMLFeedSpider
547
+
548
+ feed_type = options["feed_type"]
549
+ fields = options["fields"]
550
+ iter_tag = options["itertag"]
551
+ base = CSVFeedSpider if feed_type == "csv" else XMLFeedSpider
552
+
553
+ class Collector(base): # type: ignore[misc, valid-type]
554
+ name = f"scrapling-{crawl_id}"
555
+ start_urls = [options["feed_url"]]
556
+ allowed_domains = domains
557
+ max_pages = limit
558
+ itertag = iter_tag
559
+ robots_txt_obey = policy["obey_robots"]
560
+ download_delay = policy["delay_seconds"]
561
+ concurrent_requests = policy["concurrency"]
562
+ crawl_strategy = policy["strategy"]
563
+ autothrottle_enabled = policy["autothrottle"]
564
+
565
+ def configure_sessions(self, manager: Any) -> None:
566
+ _session_config(manager, url)
567
+
568
+ async def parse_node(self, response: Any, node: Any) -> Any:
569
+ yield {name: node.findtext(path) for name, path in fields.items()}
570
+
571
+ async def parse_row(self, response: Any, row: dict[str, Any]) -> Any:
572
+ yield {name: row.get(path) for name, path in fields.items()}
573
+
574
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
575
+ _collect_row(item, state=state, limit=limit, crawl_id=crawl_id, pause=self.pause)
576
+ return None
577
+
578
+ return Collector(crawldir=policy["checkpoint_dir"] or None)
579
+
580
+
581
+ def _shopify_sitemap_arg(mode: str, value: Any) -> Any:
582
+ """shopify 的 sitemapUrl 只收非空字符串或 null(与 _make_shopify_spider 同一条判据)。
583
+
584
+ 提前到这里判,是因为后面的 url_allowed 复核要拿它当字符串处理:先判干净,才不会把
585
+ 类型错误翻成 CRAWL_SETUP_FAILED。拆成函数也顺手把 crawl_run 的分支数压回去。
586
+
587
+ :param mode: 爬取模式
588
+ :param value: 协议参数 sitemapUrl
589
+ :returns: 原值
590
+ """
591
+ if mode == "shopify" and value is not None and (not isinstance(value, str) or not value):
592
+ from adapters import AdapterError
593
+
594
+ raise AdapterError("BAD_ARGS", "sitemapUrl must be a non-empty string or null")
595
+ return value
596
+
597
+
286
598
  def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
287
599
  """起一个后台爬虫,立刻返回 crawl id。
288
600
 
@@ -303,23 +615,82 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
303
615
  max_content_chars = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
304
616
  budget_ms = _positive_int(args.get("maxDurationMs"), "maxDurationMs", DEFAULT_MAX_RUNTIME_MS)
305
617
  strip_inline_images = _strip_inline_images(args)
618
+ css_selector = args.get("cssSelector")
619
+ if css_selector is not None and not isinstance(css_selector, str):
620
+ raise AdapterError("BAD_ARGS", "cssSelector must be a string or null")
621
+ main_content_only = args.get("mainContentOnly", True)
622
+ if not isinstance(main_content_only, bool):
623
+ raise AdapterError("BAD_ARGS", "mainContentOnly must be a boolean")
624
+ include_patterns = _crawl_patterns(args.get("includePatterns"), "includePatterns")
625
+ exclude_patterns = _crawl_patterns(args.get("excludePatterns"), "excludePatterns")
626
+ mode = args.get("mode", "content")
627
+ if mode not in ("content", "sitemap", "feed", "shopify"):
628
+ raise AdapterError("BAD_ARGS", f"mode must be content, sitemap, feed or shopify, got {mode!r}")
629
+ sitemap_url = args.get("sitemapUrl")
630
+ sitemap_follow = args.get("sitemapFollow")
631
+ feed_url = args.get("feedUrl")
632
+ feed_type = args.get("feedType")
633
+ itertag = args.get("itertag", "item")
634
+ fields = args.get("fields")
635
+ if mode == "sitemap":
636
+ if not isinstance(sitemap_url, str) or not sitemap_url:
637
+ raise AdapterError("BAD_ARGS", "sitemap mode requires sitemapUrl")
638
+ if sitemap_follow is not None:
639
+ if not isinstance(sitemap_follow, str):
640
+ raise AdapterError("BAD_ARGS", "sitemapFollow must be a string or null")
641
+ try:
642
+ re.compile(sitemap_follow)
643
+ except re.error as error:
644
+ raise AdapterError("BAD_ARGS", f"invalid sitemapFollow: {error}") from error
645
+ if mode == "feed":
646
+ if not isinstance(feed_url, str) or not feed_url:
647
+ raise AdapterError("BAD_ARGS", "feed mode requires feedUrl")
648
+ if feed_type not in ("xml", "csv"):
649
+ raise AdapterError("BAD_ARGS", "feedType must be 'xml' or 'csv'")
650
+ if not isinstance(itertag, str) or not itertag:
651
+ raise AdapterError("BAD_ARGS", "itertag must be a non-empty string")
652
+ if (
653
+ not isinstance(fields, dict)
654
+ or not fields
655
+ or any(not isinstance(key, str) or not isinstance(value, str) for key, value in fields.items())
656
+ ):
657
+ raise AdapterError("BAD_ARGS", "fields must be a non-empty {output: path} mapping of strings")
658
+ sitemap_url = _shopify_sitemap_arg(mode, sitemap_url)
306
659
  policy = _crawl_policy(args)
307
660
  crawl_id = uuid.uuid4().hex[:12]
308
661
  state: dict[str, Any] = {
309
662
  "error": None,
663
+ "mode": mode,
310
664
  "pages": [],
665
+ "rows": [],
666
+ "stats": None,
311
667
  "max_content_chars": max_content_chars,
312
668
  "strip_inline_images": strip_inline_images,
313
669
  "budget_ms": budget_ms,
314
670
  "deadline": time.monotonic() + budget_ms / 1000,
315
671
  }
316
- domains = _allowed_domains(url)
672
+ # shopify 模式真正抓的主机可以来自 sitemapUrl:_make_shopify_spider 用它的 netloc 拼
673
+ # collections/products 两个 URL。而站内判定用的是 allowed_domains —— 两处取不同来源时
674
+ # spider 发出的每个请求都会被判成站外,一页都收不到。所以主机以真正要打的那一个为准。
675
+ domain_source = sitemap_url if mode == "shopify" and sitemap_url else url
676
+ domains = _allowed_domains(domain_source)
317
677
 
318
678
  # Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
319
679
  # 的 guard.url_allowed 是同一个实现,因此两侧同解。
320
680
  allowed, reason = url_allowed(url)
321
681
  if not allowed:
322
682
  raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
683
+ # sitemap / shopify 的 sitemapUrl、feed 的 feedUrl 都是 spider 会真去请求的地址,
684
+ # 每一个都要在这里复判:只判起点的 url 等于给 sitemapUrl 留了一条不过闸的门。
685
+ for target in (
686
+ sitemap_url if mode in ("sitemap", "shopify") else None,
687
+ feed_url if mode == "feed" else None,
688
+ ):
689
+ if target is None:
690
+ continue
691
+ allowed, reason = url_allowed(target)
692
+ if not allowed:
693
+ raise AdapterError("URL_BLOCKED", f"{target}: {reason}")
323
694
 
324
695
  with _CRAWL_LOCK:
325
696
  _evict_finished_crawls()
@@ -340,7 +711,63 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
340
711
  }
341
712
 
342
713
  try:
343
- spider = _make_spider(url, max_pages, crawl_id, state, domains, policy)
714
+ if mode == "sitemap":
715
+ spider = _make_sitemap_spider(
716
+ url,
717
+ max_pages,
718
+ crawl_id,
719
+ state,
720
+ domains,
721
+ policy,
722
+ {
723
+ "sitemap_url": sitemap_url,
724
+ "sitemap_follow": sitemap_follow,
725
+ "css_selector": css_selector,
726
+ "main_content_only": main_content_only,
727
+ "include_patterns": include_patterns,
728
+ "exclude_patterns": exclude_patterns,
729
+ },
730
+ )
731
+ elif mode == "shopify":
732
+ spider = _make_shopify_spider(
733
+ url,
734
+ max_pages,
735
+ crawl_id,
736
+ state,
737
+ domains,
738
+ policy,
739
+ {"sitemap_url": sitemap_url},
740
+ )
741
+ elif mode == "feed":
742
+ spider = _make_feed_spider(
743
+ url,
744
+ max_pages,
745
+ crawl_id,
746
+ state,
747
+ domains,
748
+ policy,
749
+ {
750
+ "feed_url": feed_url,
751
+ "feed_type": feed_type,
752
+ "itertag": itertag,
753
+ "fields": fields,
754
+ },
755
+ )
756
+ else:
757
+ spider = _make_spider(
758
+ url,
759
+ max_pages,
760
+ crawl_id,
761
+ state,
762
+ domains,
763
+ policy,
764
+ {
765
+ "css_selector": css_selector,
766
+ "main_content_only": main_content_only,
767
+ "include_patterns": include_patterns,
768
+ "exclude_patterns": exclude_patterns,
769
+ },
770
+ )
344
771
  except BaseException as error:
345
772
  with _CRAWL_LOCK:
346
773
  _CRAWLS.pop(crawl_id, None)
@@ -355,7 +782,8 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
355
782
  # 线程还没跑就被叫停了(crawl_stop 在 spider 登记之前到):一页都不抓。
356
783
  return
357
784
  try:
358
- spider.start()
785
+ result = spider.start()
786
+ state["stats"] = _stats_projection(result.stats)
359
787
  except Exception as error: # noqa: BLE001
360
788
  state["error"] = f"{type(error).__name__}: {error}"
361
789
  _emit_event("crawlError", crawlId=crawl_id, text=str(error))
@@ -369,7 +797,11 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
369
797
  # 之前就先推了 progress,宿主侧「第一条是 crawlStarted」的读法于是变成随缘;二是万一这一帧
370
798
  # 发不出去(stdout 断了、序列化炸了),异常抛给调用方时蜘蛛已经在跑 —— 调用方拿不到
371
799
  # crawlId,就叫不停它,那个名额要一直占到进程退出。
372
- _emit_event("crawlStarted", crawlId=crawl_id, text=f"crawling {url} (max {max_pages} pages)")
800
+ _emit_event(
801
+ "crawlStarted",
802
+ crawlId=crawl_id,
803
+ text=f"crawling {url} in {mode} mode (max {max_pages} items)",
804
+ )
373
805
  try:
374
806
  thread.start()
375
807
  except RuntimeError:
@@ -384,12 +816,18 @@ def _is_running(entry: dict[str, Any]) -> bool:
384
816
  """这个登记条目算不算「正在跑」。
385
817
 
386
818
  ``thread`` 为 ``None`` 表示 spider 还在构造中:它已经占了并发名额,所以算在跑。
819
+ ``thread.ident`` 为 ``None`` 是另一段窗口——线程对象已登记但还没 ``start()``。只按
820
+ ``is_alive()`` 判会在这段窗口里把条目当成已结束:并发的 :func:`crawl_run` 少算一个名额
821
+ (突破并发上限)、:func:`_evict_finished_crawls` 把它当历史淘汰(之后那次 ``start()``
822
+ 就跑在没有登记项的蜘蛛上,叫不停)、:func:`crawl_stop` 判成不在跑。
387
823
 
388
824
  :param entry: 登记条目
389
825
  :returns: 是否占用名额
390
826
  """
391
827
  thread = entry.get("thread")
392
- return thread is None or thread.is_alive()
828
+ if thread is None:
829
+ return True
830
+ return thread.ident is None or thread.is_alive()
393
831
 
394
832
 
395
833
  def _evict_finished_crawls() -> None:
@@ -445,30 +883,71 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
445
883
  # pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
446
884
  # 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
447
885
  with _CRAWL_LOCK:
448
- total = len(state["pages"])
449
- pages, more = _take_pages(state["pages"], since)
886
+ feed_rows = state.get("mode") in ("feed", "shopify")
887
+ source = state["rows"] if feed_rows else state["pages"]
888
+ total = len(source)
889
+ taken, more = _take_pages(source, since)
450
890
  running = _is_running(entry)
891
+ pages = [] if feed_rows else taken
892
+ rows = taken if feed_rows else []
451
893
  return {
452
894
  "crawlId": entry["crawl_id"],
895
+ "mode": state.get("mode", "content"),
453
896
  # thread 为 None 表示 spider 还在构造中:没跑起来,但也没结束。
454
897
  "running": running,
455
898
  "pages": pages,
899
+ "rows": rows,
456
900
  "total": total,
457
901
  "more": more,
458
902
  "error": state["error"],
459
903
  # 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
460
904
  "expired": state.get("expired") is True,
905
+ # 只有 spider.start() 返回之后才完整;运行中为 null,不把「还没量到」报成 0。
906
+ "stats": state.get("stats"),
461
907
  }
462
908
 
463
909
 
910
+ def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
911
+ """把单页压到 ``budget`` 字节以内。
912
+
913
+ ``maxContentChars`` 没有上界(部署侧的 ``fetchMaxOutputChars`` 只声明了 ``min(1)``),
914
+ 所以「一页就超过回包预算」是可达的:这时 :func:`_take_pages` 若照原样把它交出去,那一帧
915
+ 会顶过 Host 的 8 MiB 切帧线,整个 sidecar 连同正在跑的会话一起被判成坏帧拆掉。宁可回
916
+ 一页被截断的正文,也不要拆进程。
917
+
918
+ 截断量按**序列化之后**的剩余空间算:先量出除 markdown 以外的固定开销,再把 markdown
919
+ 砍到剩下的额度。CJK 一个字在 UTF-8 里三字节,所以按字符砍之后还要复查一次字节数,
920
+ 复查不过就继续砍,直到装得下或已砍空。
921
+
922
+ :param page: 原始页
923
+ :param budget: 这一页的字节预算
924
+ :returns: 压过的新页(不就地改原对象,state 里留全量)
925
+ """
926
+ if "markdown" not in page:
927
+ return page
928
+ overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
929
+ room = max(0, budget - overhead)
930
+ markdown = str(page.get("markdown", ""))
931
+ clipped = markdown[:room] + "\n\n[truncated to fit the status frame budget]"
932
+ while len(clipped.encode("utf-8")) > room and clipped:
933
+ clipped = clipped[: max(0, len(clipped) - max(1, len(clipped) // 4))]
934
+ return {**page, "markdown": clipped, "truncated": True}
935
+
936
+
464
937
  def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[str, Any]], bool]:
465
938
  """从 ``since`` 起取一段页,按 :data:`MAX_STATUS_BYTES` 封顶。
466
939
 
467
- 至少回一页:单页就超预算时也回它,否则调用方永远取不到下一页,轮询变成死循环。
468
- 单页体量由 ``max_content_chars`` 兜着,一页远小于 Host 那份 8 MiB 切帧上限。
940
+ 回包条数与 ``since`` 的推进是同一件事:调用方按 ``len(pages)`` 推进 ``since``,所以
941
+ 这一轮回了哪几页,下一轮就必须从紧接着的下一页开始 —— 回包里的页得是**连续**的一段。
942
+ 早先碰到单页超预算就直接 ``return [_shrink_page(...)]``,把已经收下的前几页一起丢掉,
943
+ 而调用方只按回包条数推进一页,于是那些页下一轮被**重复**发出、更后面的页永远轮不到。
469
944
 
470
- :param all_pages - 活页表
471
- :param since - 已经读走多少页
945
+ 现在:已经收下的页一起回,当前这页压到预算内再回;当前页若挤不进本轮余量就留给下一轮
946
+ (下一轮的 ``since`` 正好落在它身上,且那一轮 ``taken`` 为空、只走截断分支),既不重复
947
+ 也不永久跳过。
948
+
949
+ :param all_pages: 活页表
950
+ :param since: 已经读走多少页
472
951
  :returns: (这一段的页, 后面还有没有)
473
952
  """
474
953
  if since >= len(all_pages):
@@ -477,6 +956,12 @@ def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[
477
956
  spent = 0
478
957
  for index in range(since, len(all_pages)):
479
958
  size = len(json.dumps(all_pages[index], ensure_ascii=False).encode("utf-8"))
959
+ if size > MAX_STATUS_BYTES:
960
+ # 当前页压到预算内,但已经收下的页必须一起回:这一轮回了 k 页,since 就前进
961
+ # k 页,缺一页就会在下一轮重发它、更后面的页则被跳过。
962
+ if taken:
963
+ return taken, True
964
+ return [_shrink_page(all_pages[index], MAX_STATUS_BYTES)], index + 1 < len(all_pages)
480
965
  if taken and spent + size > MAX_STATUS_BYTES:
481
966
  return taken, True
482
967
  taken.append(all_pages[index])
@@ -484,22 +969,12 @@ def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[
484
969
  return taken, False
485
970
 
486
971
 
487
- def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
488
- """叫停一个爬虫。
489
-
490
- 为什么必须有这条:宿主的作业取消只活在 Node 侧,Python 里的 Spider 跑在自己的
491
- 线程上,看不见它。少了这一条,「作业显示已杀」之后爬虫还在后台跑,Python 进程也
492
- 一直被一个没人管的蜘蛛占着。三条路各管一段:已经在跑的由 ``Spider.pause()`` 立刻
493
- 收尾(引擎留给外部叫停的通道,等在途请求收尾后自己退出);还没开始跑的把截止提前到
494
- 现在,并在抓到第一页之前退出。
495
-
496
- 已经跑完的爬虫叫不停(引擎已拆),那不是错误:调用的意图是「别跑了」,已经停了。
972
+ def _request_stop(entry: dict[str, Any]) -> bool:
973
+ """叫停一个登记条目:在跑的让引擎收尾,还没开跑的置标志。
497
974
 
498
- :param args: 协议参数
499
- :returns: {crawlId, stopping}
500
- :raises adapters.AdapterError: id 缺失或不存在
975
+ :param entry: 登记条目
976
+ :returns: 是否真有一只蜘蛛在跑(因而被叫停)
501
977
  """
502
- entry = _get_crawl(args.get("crawlId"))
503
978
  state: dict[str, Any] = entry["state"]
504
979
  # 截止提前到「现在」:构造中的蜘蛛、刚起线程还没抓到页的蜘蛛,都在收到第一页时停。
505
980
  state["deadline"] = time.monotonic()
@@ -509,24 +984,51 @@ def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
509
984
  if spider is None:
510
985
  # 线程还没起:置个标志,worker 起手看见它就直接退出,一页都不抓。
511
986
  entry["stop_requested"] = True
512
- stopping = False
513
987
  if spider is not None and running:
514
988
  with suppress(RuntimeError):
515
989
  spider.pause()
516
- stopping = True
517
- return {"crawlId": entry["crawl_id"], "stopping": stopping}
990
+ return True
991
+ return False
518
992
 
519
993
 
520
- def close_all_crawls() -> None:
521
- """清掉爬虫登记表。
994
+ def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
995
+ """叫停一个爬虫。
522
996
 
523
- 爬虫跑在 daemon 线程里:sidecar 退出时它们跟着退出,所以这里只清登记,
524
- 不需要(也没法)去优雅中断一个正在跑的 spider。
997
+ 为什么必须有这条:宿主的作业取消只活在 Node 侧,Python 里的 Spider 跑在自己的线程上,
998
+ 看不见它。少了这一条,「作业显示已杀」之后爬虫还在后台跑,Python 进程也被一只没人管的
999
+ 蜘蛛占着。已经跑完的叫不停(引擎已拆),那不是错误:调用的意图是「别跑了」,已经停了。
525
1000
 
526
- **它不停线程**:调用之后仍在跑的蜘蛛会继续往 stdout 推事件帧(进度、跳过、报错)。
527
- 进程退出时这无所谓,但任何「清完登记表就以为场上没蜘蛛了」的调用方都会被这件事咬到
528
- —— 要停就按 id 逐只 :func:`crawl_stop`,再等 ``thread`` 退出。
1001
+ :param args: 协议参数
1002
+ :returns: {crawlId, stopping}
1003
+ :raises adapters.AdapterError: id 缺失或不存在
529
1004
  """
1005
+ entry = _get_crawl(args.get("crawlId"))
1006
+ return {"crawlId": entry["crawl_id"], "stopping": _request_stop(entry)}
1007
+
1008
+
1009
+ def close_all_crawls() -> None:
1010
+ """叫停全部爬虫,有界地等线程退出,再清登记表。
1011
+
1012
+ sidecar 的两条收尾路径都走这里。等是**有界**的:宿主的优雅关闭只有 ``sidecarGraceMs``
1013
+ 那么久(默认 5s),拖过它只会换来一次强杀,反而更看不清是谁停的。等不到的那几只记一行
1014
+ stderr —— stdout 是与 Host 的协议通道,那里不能写。
1015
+ """
1016
+ with _CRAWL_LOCK:
1017
+ entries = list(_CRAWLS.values())
1018
+ threads: list[Any] = []
1019
+ for entry in entries:
1020
+ _request_stop(entry)
1021
+ worker = entry.get("thread")
1022
+ if worker is not None:
1023
+ threads.append(worker)
1024
+ deadline = time.monotonic() + SHUTDOWN_JOIN_SECONDS
1025
+ for worker in threads:
1026
+ # 还没 start() 的线程 join 会抛 RuntimeError;那一段窗口里本来就没有可等的东西。
1027
+ with suppress(RuntimeError):
1028
+ worker.join(timeout=max(0.0, deadline - time.monotonic()))
1029
+ stuck = sum(1 for worker in threads if worker.is_alive())
1030
+ if stuck:
1031
+ print(f"[crawl] {stuck} spider thread(s) still running at shutdown", file=sys.stderr)
530
1032
  _CRAWLS.clear()
531
1033
 
532
1034