@jayyuen66/dsh-scrapling 0.1.2 → 0.1.4

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
173
321
 
174
- class Collector(SiteToMarkdownSpider): # type: ignore[misc, valid-type]
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 []
327
+
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,290 @@ 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}",
392
+ _collect_page(
393
+ item,
394
+ state=state,
395
+ limit=limit,
396
+ crawl_id=crawl_id,
397
+ domains=domains,
398
+ pause=self.pause,
399
+ )
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
+ # 发现期的账:上游的 ``max_pages`` 只拦 ``parse()``(收页),发现期的 sitemap 请求是
429
+ # 另一条路 —— 一个 sitemapindex 指向几百个子 sitemap 时,``maxPages=2`` 照样能打出
430
+ # 几百次请求。这里给两个发现维度各设同一道上限。
431
+ # 放在类外是必须的:类体里的名字不构成方法的闭包(方法里读不到)。
432
+ discovery = {"sitemaps": 0, "urls": 0}
433
+
434
+ def _cap_discovery() -> None:
435
+ """记下「发现期被截断」这件事,让作业结果能说出为什么少。"""
436
+ if not state.get("notice"):
437
+ state["notice"] = (
438
+ f"sitemap discovery stopped at maxPages={limit}: at most {limit} child sitemaps "
439
+ f"and {limit} sitemap URLs are followed"
440
+ )
441
+
442
+ class Collector(SitemapSpider):
443
+ name = f"scrapling-{crawl_id}"
444
+ sitemap_urls = [options["sitemap_url"]]
445
+ sitemap_follow = LinkExtractor(allow=follow) if follow else None
446
+ allowed_domains = domains
447
+ max_pages = limit
448
+ css_selector = content_selector
449
+ main_content_only = body_only
450
+ robots_txt_obey = policy["obey_robots"]
451
+ download_delay = policy["delay_seconds"]
452
+ concurrent_requests = policy["concurrency"]
453
+ crawl_strategy = policy["strategy"]
454
+ autothrottle_enabled = policy["autothrottle"]
455
+
456
+ def rules(self) -> list[Any]:
457
+ if not include and not exclude:
458
+ return []
459
+ return [
460
+ CrawlRule(
461
+ LinkExtractor(allow=include or (), deny=exclude or ()),
462
+ callback=self.parse,
463
+ )
464
+ ]
465
+
466
+ def configure_sessions(self, manager: Any) -> None:
467
+ _session_config(manager, url)
468
+
469
+ async def _parse_sitemap(self, response: Any) -> Any:
470
+ """把 SitemapSpider 的发现期请求也收进 maxPages 上限。
471
+
472
+ 判两类请求:回调仍是 ``_parse_sitemap`` 的是子 sitemap 文档,其余是要抓的页面
473
+ URL;两类各自按 ``limit`` 封顶,超出的不再发出,并给作业结果留一条 notice。
474
+ """
475
+ async for request in super()._parse_sitemap(response):
476
+ is_child_sitemap = getattr(request, "callback", None) == self._parse_sitemap
477
+ key = "sitemaps" if is_child_sitemap else "urls"
478
+ if discovery[key] >= limit:
479
+ _cap_discovery()
480
+ continue
481
+ discovery[key] += 1
482
+ yield request
483
+
484
+ async def parse(self, response: Any) -> Any:
485
+ if self.max_pages and len(state["pages"]) >= self.max_pages:
486
+ return
487
+ yield {
488
+ "url": response.url,
489
+ "title": str(response.css("title::text").get() or "").strip(),
490
+ "markdown": response.markdown(self.css_selector, self.main_content_only),
491
+ }
492
+
493
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
494
+ _collect_page(
495
+ item,
496
+ state=state,
497
+ limit=limit,
498
+ crawl_id=crawl_id,
499
+ domains=domains,
500
+ pause=self.pause,
501
+ )
502
+ return None
503
+
504
+ return Collector(crawldir=policy["checkpoint_dir"] or None)
505
+
506
+
507
+ def _make_shopify_spider(
508
+ url: str,
509
+ limit: int,
510
+ crawl_id: str,
511
+ state: dict[str, Any],
512
+ domains: set[str],
513
+ policy: dict[str, Any],
514
+ options: dict[str, Any],
515
+ ) -> Any:
516
+ """ShopifySpider:走 `/collections.json` 与每个集合的 `/products.json`,按变体出行。
517
+
518
+ 上游模板把三个 URL 写死成 `https://`,而本地夹具与内网镜像常常是 http;这里按起始
519
+ URL(或 `sitemapUrl`)的 scheme 重写同一组模板,好让「同一个实现」既能打真店也能打夹具。
520
+ """
521
+ from urllib.parse import urlsplit
522
+
523
+ from scrapling.spiders import ShopifySpider
524
+
525
+ override = options.get("sitemap_url")
526
+ if override is not None and (not isinstance(override, str) or not override):
527
+ from adapters import AdapterError
528
+
529
+ raise AdapterError("BAD_ARGS", "sitemapUrl must be a non-empty string or null")
530
+ source = override or url
531
+ parts = urlsplit(source)
532
+ scheme = parts.scheme or "https"
533
+ website = parts.netloc
534
+ if not website:
535
+ raise ValueError("shopify mode needs a host in url or sitemapUrl")
536
+
537
+ class Collector(ShopifySpider):
538
+ name = f"scrapling-{crawl_id}"
539
+ target_website = website
540
+ collections_url = f"{scheme}://{{website}}/collections.json?page={{page}}&limit=250"
541
+ products_url = f"{scheme}://{{website}}/collections/{{handle}}/products.json?page={{page}}&limit=250"
542
+ product_url = f"{scheme}://{{website}}/collections/{{handle}}/products/{{product_handle}}"
543
+ allowed_domains = domains
544
+ robots_txt_obey = policy["obey_robots"]
545
+ download_delay = policy["delay_seconds"]
546
+ concurrent_requests = policy["concurrency"]
547
+ autothrottle_enabled = policy["autothrottle"]
548
+
549
+ def configure_sessions(self, manager: Any) -> None:
550
+ # 代理判定跟着**真正要打的主机**走:shopify 的 collections/products 是用
551
+ # sitemapUrl(或 url)的 netloc 拼出来的,与 url 可能不是同一台。
552
+ _session_config(manager, source)
553
+
554
+ def _not_a_store(self, response: Any, expected: str) -> str | None:
555
+ """判断这次响应是不是「不是 Shopify 店铺」;是则回一条人读的原因。
556
+
557
+ 上游模板对 ``response.json()["collections"]`` 直接下标:站点回 404 页或一张
558
+ HTML 首页时,异常被引擎吞进日志,作业就这么「completed、0 行」,模型看不出
559
+ 是打错了站还是抓早了。这里把三种常见形态折成一句可断言的话。
560
+ """
561
+ status = getattr(response, "status", 200)
562
+ where = str(getattr(response, "url", "") or source)
563
+ if status != 200:
564
+ return (
565
+ f"shopify source answered HTTP {status} for {where}; "
566
+ f"the response is not Shopify store JSON (expected {expected}.json)"
567
+ )
568
+ try:
569
+ payload = response.json()
570
+ except Exception: # noqa: BLE001 —— 上游 json() 的异常类型随响应体变
571
+ return (
572
+ f"shopify source returned a non-JSON body for {where}; "
573
+ f"the response is not Shopify store JSON (expected {expected}.json)"
242
574
  )
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",
575
+ if not isinstance(payload, dict) or not isinstance(payload.get(expected), list):
576
+ return (
577
+ f"shopify source returned JSON without a {expected!r} list for {where}; "
578
+ f"the response is not Shopify store JSON (expected {expected}.json)"
253
579
  )
580
+ return None
581
+
582
+ def _note(self, notice: str) -> None:
583
+ """只在第一条 notice 上落笔:同一份结果里留最先出现的那个原因。"""
584
+ if not state.get("notice"):
585
+ state["notice"] = notice
586
+
587
+ async def parse(self, response: Any) -> Any:
588
+ notice = self._not_a_store(response, "collections")
589
+ if notice is not None:
590
+ self._note(notice)
591
+ return
592
+ async for item in super().parse(response):
593
+ yield item
594
+
595
+ async def parse_collection(self, response: Any) -> Any:
596
+ notice = self._not_a_store(response, "products")
597
+ if notice is not None:
598
+ self._note(notice)
599
+ return
600
+ async for item in super().parse_collection(response):
601
+ yield item
602
+
603
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
604
+ _collect_row(item, state=state, limit=limit, crawl_id=crawl_id, pause=self.pause)
605
+ if len(state["rows"]) >= limit:
606
+ # 集合分页对真店是有限的,但没有上限的目录会让作业一直跑下去;到量就叫停。
254
607
  with suppress(RuntimeError):
255
608
  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
- }
273
- )
274
- _emit_event(
275
- "progress",
276
- crawlId=crawl_id,
277
- done=len(pages),
278
- limit=limit,
279
- text=f"{len(pages)}/{limit} {page_url}",
280
- )
281
609
  return None
282
610
 
283
611
  return Collector(crawldir=policy["checkpoint_dir"] or None)
284
612
 
285
613
 
614
+ def _make_feed_spider(
615
+ url: str,
616
+ limit: int,
617
+ crawl_id: str,
618
+ state: dict[str, Any],
619
+ domains: set[str],
620
+ policy: dict[str, Any],
621
+ options: dict[str, Any],
622
+ ) -> Any:
623
+ """XMLFeedSpider / CSVFeedSpider:按 fields 映射出行,不抓页面。"""
624
+ from scrapling.spiders import CSVFeedSpider, XMLFeedSpider
625
+
626
+ feed_type = options["feed_type"]
627
+ fields = options["fields"]
628
+ iter_tag = options["itertag"]
629
+ base = CSVFeedSpider if feed_type == "csv" else XMLFeedSpider
630
+
631
+ class Collector(base): # type: ignore[misc, valid-type]
632
+ name = f"scrapling-{crawl_id}"
633
+ start_urls = [options["feed_url"]]
634
+ allowed_domains = domains
635
+ max_pages = limit
636
+ itertag = iter_tag
637
+ robots_txt_obey = policy["obey_robots"]
638
+ download_delay = policy["delay_seconds"]
639
+ concurrent_requests = policy["concurrency"]
640
+ crawl_strategy = policy["strategy"]
641
+ autothrottle_enabled = policy["autothrottle"]
642
+
643
+ def configure_sessions(self, manager: Any) -> None:
644
+ _session_config(manager, url)
645
+
646
+ async def parse_node(self, response: Any, node: Any) -> Any:
647
+ yield {name: node.findtext(path) for name, path in fields.items()}
648
+
649
+ async def parse_row(self, response: Any, row: dict[str, Any]) -> Any:
650
+ yield {name: row.get(path) for name, path in fields.items()}
651
+
652
+ async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
653
+ _collect_row(item, state=state, limit=limit, crawl_id=crawl_id, pause=self.pause)
654
+ return None
655
+
656
+ return Collector(crawldir=policy["checkpoint_dir"] or None)
657
+
658
+
659
+ def _shopify_sitemap_arg(mode: str, value: Any) -> Any:
660
+ """shopify 的 sitemapUrl 只收非空字符串或 null(与 _make_shopify_spider 同一条判据)。
661
+
662
+ 提前到这里判,是因为后面的 url_allowed 复核要拿它当字符串处理:先判干净,才不会把
663
+ 类型错误翻成 CRAWL_SETUP_FAILED。拆成函数也顺手把 crawl_run 的分支数压回去。
664
+
665
+ :param mode: 爬取模式
666
+ :param value: 协议参数 sitemapUrl
667
+ :returns: 原值
668
+ """
669
+ if mode == "shopify" and value is not None and (not isinstance(value, str) or not value):
670
+ from adapters import AdapterError
671
+
672
+ raise AdapterError("BAD_ARGS", "sitemapUrl must be a non-empty string or null")
673
+ return value
674
+
675
+
286
676
  def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
287
677
  """起一个后台爬虫,立刻返回 crawl id。
288
678
 
@@ -303,23 +693,83 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
303
693
  max_content_chars = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
304
694
  budget_ms = _positive_int(args.get("maxDurationMs"), "maxDurationMs", DEFAULT_MAX_RUNTIME_MS)
305
695
  strip_inline_images = _strip_inline_images(args)
696
+ css_selector = args.get("cssSelector")
697
+ if css_selector is not None and not isinstance(css_selector, str):
698
+ raise AdapterError("BAD_ARGS", "cssSelector must be a string or null")
699
+ main_content_only = args.get("mainContentOnly", True)
700
+ if not isinstance(main_content_only, bool):
701
+ raise AdapterError("BAD_ARGS", "mainContentOnly must be a boolean")
702
+ include_patterns = _crawl_patterns(args.get("includePatterns"), "includePatterns")
703
+ exclude_patterns = _crawl_patterns(args.get("excludePatterns"), "excludePatterns")
704
+ mode = args.get("mode", "content")
705
+ if mode not in ("content", "sitemap", "feed", "shopify"):
706
+ raise AdapterError("BAD_ARGS", f"mode must be content, sitemap, feed or shopify, got {mode!r}")
707
+ sitemap_url = args.get("sitemapUrl")
708
+ sitemap_follow = args.get("sitemapFollow")
709
+ feed_url = args.get("feedUrl")
710
+ feed_type = args.get("feedType")
711
+ itertag = args.get("itertag", "item")
712
+ fields = args.get("fields")
713
+ if mode == "sitemap":
714
+ if not isinstance(sitemap_url, str) or not sitemap_url:
715
+ raise AdapterError("BAD_ARGS", "sitemap mode requires sitemapUrl")
716
+ if sitemap_follow is not None:
717
+ if not isinstance(sitemap_follow, str):
718
+ raise AdapterError("BAD_ARGS", "sitemapFollow must be a string or null")
719
+ try:
720
+ re.compile(sitemap_follow)
721
+ except re.error as error:
722
+ raise AdapterError("BAD_ARGS", f"invalid sitemapFollow: {error}") from error
723
+ if mode == "feed":
724
+ if not isinstance(feed_url, str) or not feed_url:
725
+ raise AdapterError("BAD_ARGS", "feed mode requires feedUrl")
726
+ if feed_type not in ("xml", "csv"):
727
+ raise AdapterError("BAD_ARGS", "feedType must be 'xml' or 'csv'")
728
+ if not isinstance(itertag, str) or not itertag:
729
+ raise AdapterError("BAD_ARGS", "itertag must be a non-empty string")
730
+ if (
731
+ not isinstance(fields, dict)
732
+ or not fields
733
+ or any(not isinstance(key, str) or not isinstance(value, str) for key, value in fields.items())
734
+ ):
735
+ raise AdapterError("BAD_ARGS", "fields must be a non-empty {output: path} mapping of strings")
736
+ sitemap_url = _shopify_sitemap_arg(mode, sitemap_url)
306
737
  policy = _crawl_policy(args)
307
738
  crawl_id = uuid.uuid4().hex[:12]
308
739
  state: dict[str, Any] = {
309
740
  "error": None,
741
+ "mode": mode,
310
742
  "pages": [],
743
+ "rows": [],
744
+ "stats": None,
311
745
  "max_content_chars": max_content_chars,
312
746
  "strip_inline_images": strip_inline_images,
313
747
  "budget_ms": budget_ms,
314
748
  "deadline": time.monotonic() + budget_ms / 1000,
749
+ "notice": "",
315
750
  }
316
- domains = _allowed_domains(url)
751
+ # shopify 模式真正抓的主机可以来自 sitemapUrl:_make_shopify_spider 用它的 netloc 拼
752
+ # collections/products 两个 URL。而站内判定用的是 allowed_domains —— 两处取不同来源时
753
+ # spider 发出的每个请求都会被判成站外,一页都收不到。所以主机以真正要打的那一个为准。
754
+ domain_source = sitemap_url if mode == "shopify" and sitemap_url else url
755
+ domains = _allowed_domains(domain_source)
317
756
 
318
757
  # Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
319
758
  # 的 guard.url_allowed 是同一个实现,因此两侧同解。
320
759
  allowed, reason = url_allowed(url)
321
760
  if not allowed:
322
761
  raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
762
+ # sitemap / shopify 的 sitemapUrl、feed 的 feedUrl 都是 spider 会真去请求的地址,
763
+ # 每一个都要在这里复判:只判起点的 url 等于给 sitemapUrl 留了一条不过闸的门。
764
+ for target in (
765
+ sitemap_url if mode in ("sitemap", "shopify") else None,
766
+ feed_url if mode == "feed" else None,
767
+ ):
768
+ if target is None:
769
+ continue
770
+ allowed, reason = url_allowed(target)
771
+ if not allowed:
772
+ raise AdapterError("URL_BLOCKED", f"{target}: {reason}")
323
773
 
324
774
  with _CRAWL_LOCK:
325
775
  _evict_finished_crawls()
@@ -340,7 +790,63 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
340
790
  }
341
791
 
342
792
  try:
343
- spider = _make_spider(url, max_pages, crawl_id, state, domains, policy)
793
+ if mode == "sitemap":
794
+ spider = _make_sitemap_spider(
795
+ url,
796
+ max_pages,
797
+ crawl_id,
798
+ state,
799
+ domains,
800
+ policy,
801
+ {
802
+ "sitemap_url": sitemap_url,
803
+ "sitemap_follow": sitemap_follow,
804
+ "css_selector": css_selector,
805
+ "main_content_only": main_content_only,
806
+ "include_patterns": include_patterns,
807
+ "exclude_patterns": exclude_patterns,
808
+ },
809
+ )
810
+ elif mode == "shopify":
811
+ spider = _make_shopify_spider(
812
+ url,
813
+ max_pages,
814
+ crawl_id,
815
+ state,
816
+ domains,
817
+ policy,
818
+ {"sitemap_url": sitemap_url},
819
+ )
820
+ elif mode == "feed":
821
+ spider = _make_feed_spider(
822
+ url,
823
+ max_pages,
824
+ crawl_id,
825
+ state,
826
+ domains,
827
+ policy,
828
+ {
829
+ "feed_url": feed_url,
830
+ "feed_type": feed_type,
831
+ "itertag": itertag,
832
+ "fields": fields,
833
+ },
834
+ )
835
+ else:
836
+ spider = _make_spider(
837
+ url,
838
+ max_pages,
839
+ crawl_id,
840
+ state,
841
+ domains,
842
+ policy,
843
+ {
844
+ "css_selector": css_selector,
845
+ "main_content_only": main_content_only,
846
+ "include_patterns": include_patterns,
847
+ "exclude_patterns": exclude_patterns,
848
+ },
849
+ )
344
850
  except BaseException as error:
345
851
  with _CRAWL_LOCK:
346
852
  _CRAWLS.pop(crawl_id, None)
@@ -355,7 +861,8 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
355
861
  # 线程还没跑就被叫停了(crawl_stop 在 spider 登记之前到):一页都不抓。
356
862
  return
357
863
  try:
358
- spider.start()
864
+ result = spider.start()
865
+ state["stats"] = _stats_projection(result.stats)
359
866
  except Exception as error: # noqa: BLE001
360
867
  state["error"] = f"{type(error).__name__}: {error}"
361
868
  _emit_event("crawlError", crawlId=crawl_id, text=str(error))
@@ -369,7 +876,11 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
369
876
  # 之前就先推了 progress,宿主侧「第一条是 crawlStarted」的读法于是变成随缘;二是万一这一帧
370
877
  # 发不出去(stdout 断了、序列化炸了),异常抛给调用方时蜘蛛已经在跑 —— 调用方拿不到
371
878
  # crawlId,就叫不停它,那个名额要一直占到进程退出。
372
- _emit_event("crawlStarted", crawlId=crawl_id, text=f"crawling {url} (max {max_pages} pages)")
879
+ _emit_event(
880
+ "crawlStarted",
881
+ crawlId=crawl_id,
882
+ text=f"crawling {url} in {mode} mode (max {max_pages} items)",
883
+ )
373
884
  try:
374
885
  thread.start()
375
886
  except RuntimeError:
@@ -451,19 +962,30 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
451
962
  # pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
452
963
  # 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
453
964
  with _CRAWL_LOCK:
454
- total = len(state["pages"])
455
- pages, more = _take_pages(state["pages"], since)
965
+ feed_rows = state.get("mode") in ("feed", "shopify")
966
+ source = state["rows"] if feed_rows else state["pages"]
967
+ total = len(source)
968
+ taken, more = _take_pages(source, since)
456
969
  running = _is_running(entry)
970
+ pages = [] if feed_rows else taken
971
+ rows = taken if feed_rows else []
457
972
  return {
458
973
  "crawlId": entry["crawl_id"],
974
+ "mode": state.get("mode", "content"),
459
975
  # thread 为 None 表示 spider 还在构造中:没跑起来,但也没结束。
460
976
  "running": running,
461
977
  "pages": pages,
978
+ "rows": rows,
462
979
  "total": total,
463
980
  "more": more,
464
981
  "error": state["error"],
982
+ # 作业自己知道的可读原因(sitemap 发现期被截断、shopify 源不是店铺 JSON 等):
983
+ # 缺了它,「0 条结果」与「站点不是那个形态」在模型眼里长得一样。
984
+ "notice": state.get("notice", ""),
465
985
  # 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
466
986
  "expired": state.get("expired") is True,
987
+ # 只有 spider.start() 返回之后才完整;运行中为 null,不把「还没量到」报成 0。
988
+ "stats": state.get("stats"),
467
989
  }
468
990
 
469
991
 
@@ -483,6 +1005,8 @@ def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
483
1005
  :param budget: 这一页的字节预算
484
1006
  :returns: 压过的新页(不就地改原对象,state 里留全量)
485
1007
  """
1008
+ if "markdown" not in page:
1009
+ return page
486
1010
  overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
487
1011
  room = max(0, budget - overhead)
488
1012
  markdown = str(page.get("markdown", ""))
@@ -495,8 +1019,14 @@ def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
495
1019
  def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[str, Any]], bool]:
496
1020
  """从 ``since`` 起取一段页,按 :data:`MAX_STATUS_BYTES` 封顶。
497
1021
 
498
- 至少回一页:单页就超预算时也回它,否则调用方永远取不到下一页,轮询变成死循环。但这一
499
- 页必须**压到预算之内**再回 —— 原样交出去的那一帧会顶过 Host 的 8 MiB 切帧线。
1022
+ 回包条数与 ``since`` 的推进是同一件事:调用方按 ``len(pages)`` 推进 ``since``,所以
1023
+ 这一轮回了哪几页,下一轮就必须从紧接着的下一页开始 —— 回包里的页得是**连续**的一段。
1024
+ 早先碰到单页超预算就直接 ``return [_shrink_page(...)]``,把已经收下的前几页一起丢掉,
1025
+ 而调用方只按回包条数推进一页,于是那些页下一轮被**重复**发出、更后面的页永远轮不到。
1026
+
1027
+ 现在:已经收下的页一起回,当前这页压到预算内再回;当前页若挤不进本轮余量就留给下一轮
1028
+ (下一轮的 ``since`` 正好落在它身上,且那一轮 ``taken`` 为空、只走截断分支),既不重复
1029
+ 也不永久跳过。
500
1030
 
501
1031
  :param all_pages: 活页表
502
1032
  :param since: 已经读走多少页
@@ -509,7 +1039,10 @@ def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[
509
1039
  for index in range(since, len(all_pages)):
510
1040
  size = len(json.dumps(all_pages[index], ensure_ascii=False).encode("utf-8"))
511
1041
  if size > MAX_STATUS_BYTES:
512
- # 单页就超预算:压到预算内回它,并置 more 让调用方知道后面还有(或还有别的页)。
1042
+ # 当前页压到预算内,但已经收下的页必须一起回:这一轮回了 k 页,since 就前进
1043
+ # k 页,缺一页就会在下一轮重发它、更后面的页则被跳过。
1044
+ if taken:
1045
+ return taken, True
513
1046
  return [_shrink_page(all_pages[index], MAX_STATUS_BYTES)], index + 1 < len(all_pages)
514
1047
  if taken and spent + size > MAX_STATUS_BYTES:
515
1048
  return taken, True
@@ -518,22 +1051,12 @@ def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[
518
1051
  return taken, False
519
1052
 
520
1053
 
521
- def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
522
- """叫停一个爬虫。
523
-
524
- 为什么必须有这条:宿主的作业取消只活在 Node 侧,Python 里的 Spider 跑在自己的
525
- 线程上,看不见它。少了这一条,「作业显示已杀」之后爬虫还在后台跑,Python 进程也
526
- 一直被一个没人管的蜘蛛占着。三条路各管一段:已经在跑的由 ``Spider.pause()`` 立刻
527
- 收尾(引擎留给外部叫停的通道,等在途请求收尾后自己退出);还没开始跑的把截止提前到
528
- 现在,并在抓到第一页之前退出。
529
-
530
- 已经跑完的爬虫叫不停(引擎已拆),那不是错误:调用的意图是「别跑了」,已经停了。
1054
+ def _request_stop(entry: dict[str, Any]) -> bool:
1055
+ """叫停一个登记条目:在跑的让引擎收尾,还没开跑的置标志。
531
1056
 
532
- :param args: 协议参数
533
- :returns: {crawlId, stopping}
534
- :raises adapters.AdapterError: id 缺失或不存在
1057
+ :param entry: 登记条目
1058
+ :returns: 是否真有一只蜘蛛在跑(因而被叫停)
535
1059
  """
536
- entry = _get_crawl(args.get("crawlId"))
537
1060
  state: dict[str, Any] = entry["state"]
538
1061
  # 截止提前到「现在」:构造中的蜘蛛、刚起线程还没抓到页的蜘蛛,都在收到第一页时停。
539
1062
  state["deadline"] = time.monotonic()
@@ -543,24 +1066,51 @@ def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
543
1066
  if spider is None:
544
1067
  # 线程还没起:置个标志,worker 起手看见它就直接退出,一页都不抓。
545
1068
  entry["stop_requested"] = True
546
- stopping = False
547
1069
  if spider is not None and running:
548
1070
  with suppress(RuntimeError):
549
1071
  spider.pause()
550
- stopping = True
551
- return {"crawlId": entry["crawl_id"], "stopping": stopping}
1072
+ return True
1073
+ return False
552
1074
 
553
1075
 
554
- def close_all_crawls() -> None:
555
- """清掉爬虫登记表。
1076
+ def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
1077
+ """叫停一个爬虫。
556
1078
 
557
- 爬虫跑在 daemon 线程里:sidecar 退出时它们跟着退出,所以这里只清登记,
558
- 不需要(也没法)去优雅中断一个正在跑的 spider。
1079
+ 为什么必须有这条:宿主的作业取消只活在 Node 侧,Python 里的 Spider 跑在自己的线程上,
1080
+ 看不见它。少了这一条,「作业显示已杀」之后爬虫还在后台跑,Python 进程也被一只没人管的
1081
+ 蜘蛛占着。已经跑完的叫不停(引擎已拆),那不是错误:调用的意图是「别跑了」,已经停了。
559
1082
 
560
- **它不停线程**:调用之后仍在跑的蜘蛛会继续往 stdout 推事件帧(进度、跳过、报错)。
561
- 进程退出时这无所谓,但任何「清完登记表就以为场上没蜘蛛了」的调用方都会被这件事咬到
562
- —— 要停就按 id 逐只 :func:`crawl_stop`,再等 ``thread`` 退出。
1083
+ :param args: 协议参数
1084
+ :returns: {crawlId, stopping}
1085
+ :raises adapters.AdapterError: id 缺失或不存在
563
1086
  """
1087
+ entry = _get_crawl(args.get("crawlId"))
1088
+ return {"crawlId": entry["crawl_id"], "stopping": _request_stop(entry)}
1089
+
1090
+
1091
+ def close_all_crawls() -> None:
1092
+ """叫停全部爬虫,有界地等线程退出,再清登记表。
1093
+
1094
+ sidecar 的两条收尾路径都走这里。等是**有界**的:宿主的优雅关闭只有 ``sidecarGraceMs``
1095
+ 那么久(默认 5s),拖过它只会换来一次强杀,反而更看不清是谁停的。等不到的那几只记一行
1096
+ stderr —— stdout 是与 Host 的协议通道,那里不能写。
1097
+ """
1098
+ with _CRAWL_LOCK:
1099
+ entries = list(_CRAWLS.values())
1100
+ threads: list[Any] = []
1101
+ for entry in entries:
1102
+ _request_stop(entry)
1103
+ worker = entry.get("thread")
1104
+ if worker is not None:
1105
+ threads.append(worker)
1106
+ deadline = time.monotonic() + SHUTDOWN_JOIN_SECONDS
1107
+ for worker in threads:
1108
+ # 还没 start() 的线程 join 会抛 RuntimeError;那一段窗口里本来就没有可等的东西。
1109
+ with suppress(RuntimeError):
1110
+ worker.join(timeout=max(0.0, deadline - time.monotonic()))
1111
+ stuck = sum(1 for worker in threads if worker.is_alive())
1112
+ if stuck:
1113
+ print(f"[crawl] {stuck} spider thread(s) still running at shutdown", file=sys.stderr)
564
1114
  _CRAWLS.clear()
565
1115
 
566
1116