@jayyuen66/dsh-scrapling 0.1.3 → 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/CHANGELOG.md +20 -0
- package/README.md +2 -1
- package/README.zh-CN.md +2 -1
- package/bin/dsh-scrapling.mjs +9 -9
- package/cordis.patch.yml +1 -1
- package/host.js +22 -21
- package/package.json +1 -1
- package/py/adapters.py +59 -5
- package/py/crawl.py +82 -0
- package/py/media.py +79 -4
package/package.json
CHANGED
package/py/adapters.py
CHANGED
|
@@ -596,6 +596,36 @@ def _static_request_payload(args: dict[str, Any], method: str) -> dict[str, Any]
|
|
|
596
596
|
return payload
|
|
597
597
|
|
|
598
598
|
|
|
599
|
+
# 请求体本身就是写意图:给了这些键却把方法留空时按 POST 发,而不是把它们丢进一次
|
|
600
|
+
# GET(那会「发出去但语义错了」,而回包上没有任何一行能看出这件事)。
|
|
601
|
+
_WRITE_BODY_KEYS = ("form", "json", "body")
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _static_method(args: dict[str, Any]) -> str:
|
|
605
|
+
"""定静态抓取的方法:显式 ``method`` 优先,没给时由请求体推。
|
|
606
|
+
|
|
607
|
+
缺省一律 GET 的写法会让 ``form`` / ``json`` / ``body`` **静默落地**:请求照发、
|
|
608
|
+
对端收到空体。所以这三个键在场时默认按 POST 发;而显式 GET 配它们是无解的组
|
|
609
|
+
合 —— 那是参数错误,不是可以静默降级的默认值。
|
|
610
|
+
|
|
611
|
+
:param args: 协议参数
|
|
612
|
+
:returns: ``GET`` / ``POST`` / ``PUT`` / ``DELETE``
|
|
613
|
+
:raises AdapterError: 方法不支持,或显式 GET 带了请求体
|
|
614
|
+
"""
|
|
615
|
+
raw = args.get("method")
|
|
616
|
+
method = str(raw).upper() if raw is not None and raw != "" else ""
|
|
617
|
+
if not method:
|
|
618
|
+
return "POST" if any(args.get(key) is not None for key in _WRITE_BODY_KEYS) else "GET"
|
|
619
|
+
if method not in ("GET", "POST", "PUT", "DELETE"):
|
|
620
|
+
raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
|
|
621
|
+
if method == "GET" and any(args.get(key) is not None for key in _WRITE_BODY_KEYS):
|
|
622
|
+
raise AdapterError(
|
|
623
|
+
"BAD_ARGS",
|
|
624
|
+
"GET cannot carry a request body; drop body/form/json or use a write method such as POST",
|
|
625
|
+
)
|
|
626
|
+
return method
|
|
627
|
+
|
|
628
|
+
|
|
599
629
|
def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
600
630
|
"""静态抓取(curl_cffi)。不需要浏览器。
|
|
601
631
|
|
|
@@ -606,9 +636,7 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
606
636
|
_require(Fetcher)
|
|
607
637
|
url = _url(args)
|
|
608
638
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
609
|
-
method =
|
|
610
|
-
if method not in ("GET", "POST", "PUT", "DELETE"):
|
|
611
|
-
raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
|
|
639
|
+
method = _static_method(args)
|
|
612
640
|
request_payload = _static_request_payload(args, method)
|
|
613
641
|
if method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
614
642
|
# 这一侧是硬拒,不依赖 Host 有没有把入参摆出来:手搓一帧 stdin 也写不出去。
|
|
@@ -630,7 +658,18 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
630
658
|
allowed, reason = guard.url_allowed(url)
|
|
631
659
|
if not allowed:
|
|
632
660
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
633
|
-
|
|
661
|
+
try:
|
|
662
|
+
response = getattr(Fetcher, method.lower())(url, **params)
|
|
663
|
+
except Exception as error:
|
|
664
|
+
# 非法的 impersonate 不是「抓取失败」而是参数错误:curl_cffi 在**请求时**才
|
|
665
|
+
# 校验它,抛的是 ``ImpersonateError``(构造 Session 那一层不校验,所以只能在
|
|
666
|
+
# 这里接)。原文与堆栈对模型没有信息量,换成一句能自己纠正的 BAD_ARGS。
|
|
667
|
+
if type(error).__name__ == "ImpersonateError":
|
|
668
|
+
raise AdapterError(
|
|
669
|
+
"BAD_ARGS",
|
|
670
|
+
f"impersonate {impersonate!r} is not supported by curl_cffi; use one of its supported browser presets",
|
|
671
|
+
) from error
|
|
672
|
+
raise
|
|
634
673
|
return to_payload(
|
|
635
674
|
response,
|
|
636
675
|
extraction_type=extraction_type,
|
|
@@ -1730,6 +1769,14 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1730
1769
|
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
1731
1770
|
)
|
|
1732
1771
|
static_params = _static_params(args, url)
|
|
1772
|
+
# extraHeaders 在浏览器那条路是请求头(上游的 extra_headers),static 这条路
|
|
1773
|
+
# 没有同名旋钮 —— 不合并的话它会被静默丢掉:调用成功、对端却没收到那个头。
|
|
1774
|
+
# 同名键以 extraHeaders 为准(它比 headers 更具体,也是浏览器侧的语义)。
|
|
1775
|
+
extra_headers = _string_map(args.get("extraHeaders"), "extraHeaders")
|
|
1776
|
+
if extra_headers is not None:
|
|
1777
|
+
merged = dict(static_params.get("headers") or {})
|
|
1778
|
+
merged.update(extra_headers)
|
|
1779
|
+
static_params["headers"] = merged
|
|
1733
1780
|
static_params.update(_static_request_payload(args, static_method))
|
|
1734
1781
|
response = getattr(session, static_method.lower())(url, **static_params)
|
|
1735
1782
|
else:
|
|
@@ -2119,7 +2166,14 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
2119
2166
|
Path(target).chmod(0o600)
|
|
2120
2167
|
else:
|
|
2121
2168
|
worker.run(lambda: session.load_state(target))
|
|
2122
|
-
except
|
|
2169
|
+
except FileNotFoundError as error:
|
|
2170
|
+
# 上游的原文里带着**宿主绝对路径**(「[Errno 2] No such file or directory:
|
|
2171
|
+
# '/Users/…/login.json'」):那是部署面的信息,对模型既没用又是泄露。点名
|
|
2172
|
+
# 那个模型自己给的文件名就够了。
|
|
2173
|
+
raise AdapterError("STATE_FAILED", f"state file does not exist: {Path(target).name}") from error
|
|
2174
|
+
except json.JSONDecodeError as error:
|
|
2175
|
+
raise AdapterError("STATE_FAILED", f"state file is not valid JSON: {Path(target).name}") from error
|
|
2176
|
+
except Exception as error: # 上游的其余文件/JSON 错误一律翻成可路由的码
|
|
2123
2177
|
raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
|
|
2124
2178
|
return {"sessionId": session_id, "path": target, "saved": saving}
|
|
2125
2179
|
|
package/py/crawl.py
CHANGED
|
@@ -425,6 +425,20 @@ def _make_sitemap_spider(
|
|
|
425
425
|
content_selector = options["css_selector"]
|
|
426
426
|
body_only = options["main_content_only"]
|
|
427
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
|
+
|
|
428
442
|
class Collector(SitemapSpider):
|
|
429
443
|
name = f"scrapling-{crawl_id}"
|
|
430
444
|
sitemap_urls = [options["sitemap_url"]]
|
|
@@ -452,6 +466,21 @@ def _make_sitemap_spider(
|
|
|
452
466
|
def configure_sessions(self, manager: Any) -> None:
|
|
453
467
|
_session_config(manager, url)
|
|
454
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
|
+
|
|
455
484
|
async def parse(self, response: Any) -> Any:
|
|
456
485
|
if self.max_pages and len(state["pages"]) >= self.max_pages:
|
|
457
486
|
return
|
|
@@ -522,6 +551,55 @@ def _make_shopify_spider(
|
|
|
522
551
|
# sitemapUrl(或 url)的 netloc 拼出来的,与 url 可能不是同一台。
|
|
523
552
|
_session_config(manager, source)
|
|
524
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)"
|
|
574
|
+
)
|
|
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)"
|
|
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
|
+
|
|
525
603
|
async def on_scraped_item(self, item: dict[str, Any]) -> dict[str, Any] | None:
|
|
526
604
|
_collect_row(item, state=state, limit=limit, crawl_id=crawl_id, pause=self.pause)
|
|
527
605
|
if len(state["rows"]) >= limit:
|
|
@@ -668,6 +746,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
668
746
|
"strip_inline_images": strip_inline_images,
|
|
669
747
|
"budget_ms": budget_ms,
|
|
670
748
|
"deadline": time.monotonic() + budget_ms / 1000,
|
|
749
|
+
"notice": "",
|
|
671
750
|
}
|
|
672
751
|
# shopify 模式真正抓的主机可以来自 sitemapUrl:_make_shopify_spider 用它的 netloc 拼
|
|
673
752
|
# collections/products 两个 URL。而站内判定用的是 allowed_domains —— 两处取不同来源时
|
|
@@ -900,6 +979,9 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
900
979
|
"total": total,
|
|
901
980
|
"more": more,
|
|
902
981
|
"error": state["error"],
|
|
982
|
+
# 作业自己知道的可读原因(sitemap 发现期被截断、shopify 源不是店铺 JSON 等):
|
|
983
|
+
# 缺了它,「0 条结果」与「站点不是那个形态」在模型眼里长得一样。
|
|
984
|
+
"notice": state.get("notice", ""),
|
|
903
985
|
# 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
|
|
904
986
|
"expired": state.get("expired") is True,
|
|
905
987
|
# 只有 spider.start() 返回之后才完整;运行中为 null,不把「还没量到」报成 0。
|
package/py/media.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import base64
|
|
6
|
+
import contextlib
|
|
6
7
|
import hashlib
|
|
7
8
|
import os
|
|
8
9
|
import struct
|
|
@@ -205,12 +206,12 @@ def _download_via_stream(
|
|
|
205
206
|
try:
|
|
206
207
|
session = curl_requests.Session(**session_kwargs)
|
|
207
208
|
except Exception as error:
|
|
208
|
-
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}") from error
|
|
209
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
209
210
|
try:
|
|
210
211
|
try:
|
|
211
212
|
response = session.request("GET", url, **request_kwargs)
|
|
212
213
|
except Exception as error:
|
|
213
|
-
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}") from error
|
|
214
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
214
215
|
try:
|
|
215
216
|
status = int(getattr(response, "status_code", 0))
|
|
216
217
|
if not 200 <= status < 300:
|
|
@@ -299,8 +300,19 @@ def _download_via_browser(
|
|
|
299
300
|
browser_params["extra_headers"] = headers
|
|
300
301
|
try:
|
|
301
302
|
response = StealthyFetcher.fetch(url, **browser_params)
|
|
302
|
-
except Exception as error:
|
|
303
|
-
|
|
303
|
+
except Exception as error: # noqa: BLE001 —— 把附件响应换一条路走完,而不是只剩一个类名
|
|
304
|
+
# 「Page.goto: Download is starting」:Chromium 不能把「触发下载的响应」当成一次
|
|
305
|
+
# 导航,fetch 这条路对附件/二进制响应天然走不通。换成等真实的 download 事件再把它
|
|
306
|
+
# 落盘。HTML 页走不到这里(fetch 成功就原样返回),所以既有成功路径不动。
|
|
307
|
+
return _download_via_browser_attachment(
|
|
308
|
+
url,
|
|
309
|
+
name=name,
|
|
310
|
+
directory=directory,
|
|
311
|
+
limit=limit,
|
|
312
|
+
timeout=timeout,
|
|
313
|
+
headers=headers,
|
|
314
|
+
cause=error,
|
|
315
|
+
)
|
|
304
316
|
status = int(getattr(response, "status", 0))
|
|
305
317
|
if not 200 <= status < 300:
|
|
306
318
|
raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
|
|
@@ -319,6 +331,69 @@ def _download_via_browser(
|
|
|
319
331
|
}
|
|
320
332
|
|
|
321
333
|
|
|
334
|
+
def _download_via_browser_attachment(
|
|
335
|
+
url: str,
|
|
336
|
+
*,
|
|
337
|
+
name: str,
|
|
338
|
+
directory: Path,
|
|
339
|
+
limit: int,
|
|
340
|
+
timeout: float,
|
|
341
|
+
headers: dict[str, str] | None,
|
|
342
|
+
cause: BaseException,
|
|
343
|
+
) -> dict[str, Any]:
|
|
344
|
+
"""浏览器路径的附件下载:等 ``download`` 事件,而不是等一次导航。
|
|
345
|
+
|
|
346
|
+
``StealthyFetcher.fetch`` 走的是 ``page.goto``,而触发下载的响应在 Chromium 里不算
|
|
347
|
+
导航,于是它只回一句 ``Page.goto: Download is starting``。这里直接开一个会话、挂上
|
|
348
|
+
与一次性路径同一套网络守卫,然后等 Playwright 的 ``expect_download`` 把附件交出来。
|
|
349
|
+
"""
|
|
350
|
+
import guard
|
|
351
|
+
from adapters import page_setup
|
|
352
|
+
from scrapling.fetchers import StealthySession
|
|
353
|
+
|
|
354
|
+
timeout_ms = int(timeout * 1000)
|
|
355
|
+
session_params: dict[str, Any] = {"timeout": timeout_ms}
|
|
356
|
+
proxy = guard.browser_proxy(url)
|
|
357
|
+
if proxy is not None:
|
|
358
|
+
session_params["proxy"] = proxy
|
|
359
|
+
session = StealthySession(**session_params)
|
|
360
|
+
page = None
|
|
361
|
+
try:
|
|
362
|
+
session.start()
|
|
363
|
+
page = session.context.new_page()
|
|
364
|
+
page.set_default_timeout(timeout_ms)
|
|
365
|
+
page_setup(page)
|
|
366
|
+
if headers is not None:
|
|
367
|
+
page.set_extra_http_headers(headers)
|
|
368
|
+
# 一触发下载这次导航就会失败,失败本身是预期的一部分(理由见上)。
|
|
369
|
+
with page.expect_download(timeout=timeout_ms) as pending, contextlib.suppress(Exception):
|
|
370
|
+
page.goto(url, wait_until="commit")
|
|
371
|
+
download = pending.value
|
|
372
|
+
source = download.path()
|
|
373
|
+
body = Path(source).read_bytes() if source is not None else b""
|
|
374
|
+
except Exception as error:
|
|
375
|
+
raise _error(
|
|
376
|
+
"DOWNLOAD_FAILED",
|
|
377
|
+
f"download failed: {type(cause).__name__}: {cause}; attachment fallback: {type(error).__name__}: {error}",
|
|
378
|
+
) from error
|
|
379
|
+
finally:
|
|
380
|
+
if page is not None:
|
|
381
|
+
with contextlib.suppress(Exception):
|
|
382
|
+
page.close()
|
|
383
|
+
with contextlib.suppress(Exception):
|
|
384
|
+
session.close()
|
|
385
|
+
if len(body) > limit:
|
|
386
|
+
raise _error("DOWNLOAD_TOO_LARGE", f"download is {len(body)} bytes, over the {limit}-byte cap")
|
|
387
|
+
target = _commit_bytes(directory, name, body)
|
|
388
|
+
return {
|
|
389
|
+
"path": str(target),
|
|
390
|
+
"bytes": len(body),
|
|
391
|
+
"sha256": hashlib.sha256(body).hexdigest(),
|
|
392
|
+
"contentType": None,
|
|
393
|
+
"status": 200,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
|
|
322
397
|
def _image_size(data: bytes, image_type: str) -> tuple[int, int]:
|
|
323
398
|
"""从 PNG/JPEG 字节里读固有尺寸;读不出时给 (0, 0)。"""
|
|
324
399
|
if image_type == "png" and data[:8] == b"\x89PNG\r\n\x1a\n" and len(data) >= 24:
|