@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/CHANGELOG.md +176 -0
- package/LICENSE +1 -1
- package/README.md +368 -549
- package/README.zh-CN.md +362 -397
- package/THIRD_PARTY_NOTICES.md +20 -2
- package/bin/dsh-scrapling.mjs +13 -0
- package/client.js +11 -1409
- package/host.js +43 -34
- package/package.json +66 -48
- package/py/adapters.py +752 -272
- package/py/bridge.py +44 -4
- package/py/crawl.py +595 -93
- package/py/extraction.py +400 -0
- package/py/guard.py +160 -34
- package/py/media.py +399 -0
- package/py/redact.py +118 -0
- package/py/redis_storage.py +129 -0
- package/py/runtime-requirements.txt +49 -0
- package/py/search.py +404 -0
- package/py/session_page.py +240 -0
- package/runtime-manifest.json +16 -0
package/py/extraction.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""选择器查询与字段抽取的纯函数。
|
|
2
|
+
|
|
3
|
+
只做 HTML 到 Python 值的转换;不读环境、不发请求、不处理 protocol 帧。
|
|
4
|
+
`adapters.select` 负责参数错误码,`locate`/`links` 在后续任务复用这里的查询与序列化。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any, Iterable, cast
|
|
11
|
+
|
|
12
|
+
_URL_ATTRIBUTES = frozenset({"href", "src", "action"})
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _json_len(value: Any) -> int:
|
|
16
|
+
"""按 JSON 序列化后的字符数计预算;与模型看到的形状一致。"""
|
|
17
|
+
return len(json.dumps(value, ensure_ascii=False))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _resolve_url(page: Any, value: str) -> str:
|
|
21
|
+
"""把相对地址拼成绝对地址;空值或拼不出来时保留原值。"""
|
|
22
|
+
if not value:
|
|
23
|
+
return value
|
|
24
|
+
try:
|
|
25
|
+
return str(page.urljoin(value))
|
|
26
|
+
except Exception: # noqa: BLE001 —— 不是合法 URL 时保留原值比抛错更有用
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _query_type(selector: str, query_type: str | None, use_xpath: bool) -> str:
|
|
31
|
+
"""把旧的 ``useXpath`` 布尔值归一到 queryType。"""
|
|
32
|
+
return query_type or ("xpath" if use_xpath else "css")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def query_nodes(
|
|
36
|
+
page: Any,
|
|
37
|
+
selector: str,
|
|
38
|
+
query_type: str = "css",
|
|
39
|
+
*,
|
|
40
|
+
use_xpath: bool = False,
|
|
41
|
+
partial: bool = False,
|
|
42
|
+
case_sensitive: bool = False,
|
|
43
|
+
clean_match: bool = True,
|
|
44
|
+
similarity_threshold: float = 0.2,
|
|
45
|
+
ignore_attributes: Iterable[str] = ("href", "src"),
|
|
46
|
+
match_text: bool = False,
|
|
47
|
+
) -> tuple[list[Any], str]:
|
|
48
|
+
"""按 queryType 返回节点列表与一条可读说明。
|
|
49
|
+
|
|
50
|
+
``similar`` 无种子时返回空列表与说明,绝不回退成整页。
|
|
51
|
+
"""
|
|
52
|
+
if not isinstance(selector, str) or not selector:
|
|
53
|
+
raise ValueError("selector is required")
|
|
54
|
+
kind = _query_type(selector, query_type, use_xpath)
|
|
55
|
+
if kind == "css":
|
|
56
|
+
return list(page.css(selector)), ""
|
|
57
|
+
if kind == "xpath":
|
|
58
|
+
return list(page.xpath(selector)), ""
|
|
59
|
+
if kind == "text":
|
|
60
|
+
found = page.find_by_text(
|
|
61
|
+
selector,
|
|
62
|
+
first_match=False,
|
|
63
|
+
partial=partial,
|
|
64
|
+
case_sensitive=case_sensitive,
|
|
65
|
+
clean_match=clean_match,
|
|
66
|
+
)
|
|
67
|
+
return list(found or []), ""
|
|
68
|
+
if kind == "regex":
|
|
69
|
+
found = page.find_by_regex(
|
|
70
|
+
selector,
|
|
71
|
+
first_match=False,
|
|
72
|
+
case_sensitive=case_sensitive,
|
|
73
|
+
clean_match=clean_match,
|
|
74
|
+
)
|
|
75
|
+
return list(found or []), ""
|
|
76
|
+
if kind == "similar":
|
|
77
|
+
seeds = list(page.xpath(selector) if use_xpath else page.css(selector))
|
|
78
|
+
if not seeds:
|
|
79
|
+
return [], "similar seed matched nothing"
|
|
80
|
+
found = seeds[0].find_similar(
|
|
81
|
+
similarity_threshold=similarity_threshold,
|
|
82
|
+
ignore_attributes=list(ignore_attributes),
|
|
83
|
+
match_text=match_text,
|
|
84
|
+
)
|
|
85
|
+
return list(found or []), ""
|
|
86
|
+
raise ValueError(f"unknown queryType: {kind}")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def serialize_match(
|
|
90
|
+
node: Any,
|
|
91
|
+
*,
|
|
92
|
+
page: Any,
|
|
93
|
+
attribute: str | None = None,
|
|
94
|
+
include_attributes: bool = False,
|
|
95
|
+
include_html: bool = False,
|
|
96
|
+
resolve_urls: bool = False,
|
|
97
|
+
) -> dict[str, Any]:
|
|
98
|
+
"""把一条元素/文本节点归一成匹配载荷。"""
|
|
99
|
+
item: dict[str, Any] = {"tag": str(getattr(node, "tag", "") or "")}
|
|
100
|
+
if attribute:
|
|
101
|
+
value = node.attrib.get(attribute, "")
|
|
102
|
+
item["value"] = _resolve_url(page, str(value)) if resolve_urls and attribute in _URL_ATTRIBUTES else str(value)
|
|
103
|
+
else:
|
|
104
|
+
item["text"] = str(node.get_all_text(strip=True))
|
|
105
|
+
if include_html:
|
|
106
|
+
item["html"] = str(node.html_content)
|
|
107
|
+
if include_attributes:
|
|
108
|
+
item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
|
|
109
|
+
return item
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _field_spec(spec: Any) -> tuple[str, str, str | None, bool]:
|
|
113
|
+
"""把字段描述归一成 (selector, mode, attribute, all)。"""
|
|
114
|
+
selector: str
|
|
115
|
+
mode: str
|
|
116
|
+
attribute: str | None
|
|
117
|
+
many: bool
|
|
118
|
+
if isinstance(spec, str):
|
|
119
|
+
selector, mode, attribute, many = spec, "text", None, False
|
|
120
|
+
elif isinstance(spec, dict):
|
|
121
|
+
raw_selector = spec.get("selector")
|
|
122
|
+
attribute = spec.get("attribute")
|
|
123
|
+
raw_mode = spec.get("mode")
|
|
124
|
+
mode = (
|
|
125
|
+
str(raw_mode)
|
|
126
|
+
if raw_mode is not None
|
|
127
|
+
else ("attribute" if isinstance(attribute, str) and attribute else "text")
|
|
128
|
+
)
|
|
129
|
+
many = bool(spec.get("all", False))
|
|
130
|
+
if not isinstance(raw_selector, str) or not raw_selector:
|
|
131
|
+
raise ValueError("field selector is required")
|
|
132
|
+
selector = raw_selector
|
|
133
|
+
if mode not in ("text", "html", "attribute"):
|
|
134
|
+
raise ValueError(f"unknown field mode: {mode}")
|
|
135
|
+
if mode == "attribute" and (not isinstance(attribute, str) or not attribute):
|
|
136
|
+
raise ValueError("attribute mode requires an attribute name")
|
|
137
|
+
else:
|
|
138
|
+
raise ValueError("field spec must be a string or an object")
|
|
139
|
+
return selector, mode, attribute if isinstance(attribute, str) else None, many
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _select_field_nodes(node: Any, selector: str) -> list[Any]:
|
|
143
|
+
"""字段选择器相对记录节点执行;以 .// 或 / 开头时走 XPath。"""
|
|
144
|
+
if selector.startswith(".//") or selector.startswith("/"):
|
|
145
|
+
return list(node.xpath(selector))
|
|
146
|
+
return list(node.css(selector))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def field_value(
|
|
150
|
+
node: Any,
|
|
151
|
+
spec: Any,
|
|
152
|
+
*,
|
|
153
|
+
page: Any,
|
|
154
|
+
resolve_urls: bool = False,
|
|
155
|
+
) -> Any:
|
|
156
|
+
"""取一个字段的值;缺失给 None,all=true 时给列表。"""
|
|
157
|
+
selector, mode, attribute, many = _field_spec(spec)
|
|
158
|
+
found = _select_field_nodes(node, selector)
|
|
159
|
+
if many:
|
|
160
|
+
values = [_field_scalar(item, mode, attribute, page, resolve_urls) for item in found]
|
|
161
|
+
return [value for value in values if value is not None]
|
|
162
|
+
for item in found:
|
|
163
|
+
value = _field_scalar(item, mode, attribute, page, resolve_urls)
|
|
164
|
+
if value is not None:
|
|
165
|
+
return value
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _field_scalar(
|
|
170
|
+
item: Any,
|
|
171
|
+
mode: str,
|
|
172
|
+
attribute: str | None,
|
|
173
|
+
page: Any,
|
|
174
|
+
resolve_urls: bool,
|
|
175
|
+
) -> Any:
|
|
176
|
+
"""从一个命中节点取 text/html/attribute 值。"""
|
|
177
|
+
if mode == "html":
|
|
178
|
+
return str(item.html_content)
|
|
179
|
+
if mode == "attribute":
|
|
180
|
+
value = item.attrib.get(attribute or "")
|
|
181
|
+
if value is None:
|
|
182
|
+
return None
|
|
183
|
+
text = str(value)
|
|
184
|
+
return _resolve_url(page, text) if resolve_urls and (attribute or "") in _URL_ATTRIBUTES else text
|
|
185
|
+
return str(item.get_all_text(strip=True))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def collect_fields(
|
|
189
|
+
nodes: Iterable[Any],
|
|
190
|
+
fields: dict[str, Any],
|
|
191
|
+
*,
|
|
192
|
+
page: Any,
|
|
193
|
+
max_content_chars: int,
|
|
194
|
+
resolve_urls: bool = False,
|
|
195
|
+
) -> tuple[list[dict[str, Any]], bool]:
|
|
196
|
+
"""把记录节点按字段表收成行;返回 (rows, truncated)。"""
|
|
197
|
+
if not isinstance(fields, dict) or not fields:
|
|
198
|
+
raise ValueError("fields must be a non-empty object")
|
|
199
|
+
rows: list[dict[str, Any]] = []
|
|
200
|
+
spent = 0
|
|
201
|
+
truncated = False
|
|
202
|
+
for node in nodes:
|
|
203
|
+
row: dict[str, Any] = {}
|
|
204
|
+
for name, spec in fields.items():
|
|
205
|
+
value = field_value(node, spec, page=page, resolve_urls=resolve_urls)
|
|
206
|
+
room = max(0, max_content_chars - spent)
|
|
207
|
+
size = _json_len(value)
|
|
208
|
+
if size > room:
|
|
209
|
+
if isinstance(value, str):
|
|
210
|
+
# JSON 字符串带两个引号;留出它们再把正文裁到剩余预算。
|
|
211
|
+
value = value[: max(0, room - 2)]
|
|
212
|
+
size = _json_len(value)
|
|
213
|
+
truncated = True
|
|
214
|
+
spent += size
|
|
215
|
+
row[str(name)] = value
|
|
216
|
+
rows.append(row)
|
|
217
|
+
if spent >= max_content_chars:
|
|
218
|
+
truncated = True
|
|
219
|
+
break
|
|
220
|
+
return rows, truncated
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
224
|
+
"""定位元素并返回生成选择器;不发网络请求,不写 adaptive 指纹。"""
|
|
225
|
+
from scrapling.parser import Selector
|
|
226
|
+
|
|
227
|
+
html = args.get("html")
|
|
228
|
+
if not isinstance(html, str):
|
|
229
|
+
raise ValueError("html must be a string")
|
|
230
|
+
selector = args.get("selector")
|
|
231
|
+
if not isinstance(selector, str) or not selector:
|
|
232
|
+
raise ValueError("selector is required")
|
|
233
|
+
url = args.get("url")
|
|
234
|
+
if url is not None and not isinstance(url, str):
|
|
235
|
+
raise ValueError("url must be a string or null")
|
|
236
|
+
query_type = args.get("queryType")
|
|
237
|
+
if query_type is not None and not isinstance(query_type, str):
|
|
238
|
+
raise ValueError("queryType must be a string")
|
|
239
|
+
query_type = query_type or "css"
|
|
240
|
+
if query_type not in ("css", "xpath", "text", "regex", "similar"):
|
|
241
|
+
raise ValueError(f"unknown queryType: {query_type}")
|
|
242
|
+
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
243
|
+
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", 200_000)
|
|
244
|
+
include_ancestors = bool(args.get("includeAncestors", True))
|
|
245
|
+
generate_selectors = bool(args.get("generateSelectors", True))
|
|
246
|
+
page = Selector(html, url=url or "")
|
|
247
|
+
nodes, notice = query_nodes(
|
|
248
|
+
page,
|
|
249
|
+
selector,
|
|
250
|
+
query_type,
|
|
251
|
+
use_xpath=bool(args.get("useXpath", False)),
|
|
252
|
+
partial=bool(args.get("partial", False)),
|
|
253
|
+
case_sensitive=bool(args.get("caseSensitive", False)),
|
|
254
|
+
clean_match=bool(args.get("cleanMatch", True)),
|
|
255
|
+
similarity_threshold=float(args.get("similarityThreshold", 0.2)),
|
|
256
|
+
ignore_attributes=args.get("ignoreAttributes") or ("href", "src"),
|
|
257
|
+
match_text=bool(args.get("matchText", False)),
|
|
258
|
+
)
|
|
259
|
+
matches: list[dict[str, Any]] = []
|
|
260
|
+
spent = 0
|
|
261
|
+
truncated = False
|
|
262
|
+
for node in nodes:
|
|
263
|
+
if len(matches) >= limit:
|
|
264
|
+
truncated = True
|
|
265
|
+
break
|
|
266
|
+
text = str(node.get_all_text(strip=True))
|
|
267
|
+
room = max(0, budget - spent)
|
|
268
|
+
if len(text) > room:
|
|
269
|
+
text = text[:room]
|
|
270
|
+
truncated = True
|
|
271
|
+
spent += len(text)
|
|
272
|
+
item: dict[str, Any] = {
|
|
273
|
+
"tag": str(getattr(node, "tag", "") or ""),
|
|
274
|
+
"text": text,
|
|
275
|
+
"attributes": {str(key): str(value) for key, value in node.attrib.items()},
|
|
276
|
+
"cssSelector": str(node.generate_css_selector) if generate_selectors else "",
|
|
277
|
+
"xpathSelector": str(node.generate_xpath_selector) if generate_selectors else "",
|
|
278
|
+
"fullCssSelector": str(node.generate_full_css_selector) if generate_selectors else "",
|
|
279
|
+
"fullXpathSelector": str(node.generate_full_xpath_selector) if generate_selectors else "",
|
|
280
|
+
"ancestors": (
|
|
281
|
+
[
|
|
282
|
+
{
|
|
283
|
+
"tag": str(getattr(ancestor, "tag", "") or ""),
|
|
284
|
+
"attributes": {str(key): str(value) for key, value in ancestor.attrib.items()},
|
|
285
|
+
}
|
|
286
|
+
for ancestor in node.iterancestors()
|
|
287
|
+
]
|
|
288
|
+
if include_ancestors
|
|
289
|
+
else []
|
|
290
|
+
),
|
|
291
|
+
}
|
|
292
|
+
matches.append(item)
|
|
293
|
+
if spent >= budget:
|
|
294
|
+
truncated = True
|
|
295
|
+
break
|
|
296
|
+
return {
|
|
297
|
+
"count": len(nodes),
|
|
298
|
+
"truncated": truncated or len(nodes) > len(matches),
|
|
299
|
+
"matches": matches,
|
|
300
|
+
"notice": notice,
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _next_reason(text: str, url: str) -> str:
|
|
305
|
+
"""给分页候选一个可读的原因;没有命中给空串。"""
|
|
306
|
+
lowered = text.lower()
|
|
307
|
+
if "load more" in lowered:
|
|
308
|
+
return "text:load more"
|
|
309
|
+
if "next" in lowered:
|
|
310
|
+
return "text:next"
|
|
311
|
+
if "more" in lowered:
|
|
312
|
+
return "text:more"
|
|
313
|
+
lowered_url = url.lower()
|
|
314
|
+
if "page=" in lowered_url:
|
|
315
|
+
return "url:page"
|
|
316
|
+
if "/page/" in lowered_url:
|
|
317
|
+
return "url:page-path"
|
|
318
|
+
if "offset=" in lowered_url:
|
|
319
|
+
return "url:offset"
|
|
320
|
+
return ""
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def links(args: dict[str, Any]) -> dict[str, Any]:
|
|
324
|
+
"""对已有 HTML 跑 LinkExtractor,并给出分页候选。"""
|
|
325
|
+
from scrapling.parser import Selector
|
|
326
|
+
from scrapling.spiders import LinkExtractor
|
|
327
|
+
|
|
328
|
+
html = args.get("html")
|
|
329
|
+
if not isinstance(html, str):
|
|
330
|
+
raise ValueError("html must be a string")
|
|
331
|
+
base_url = args.get("baseUrl")
|
|
332
|
+
if base_url is not None and not isinstance(base_url, str):
|
|
333
|
+
raise ValueError("baseUrl must be a string or null")
|
|
334
|
+
page = Selector(html, url=base_url or "")
|
|
335
|
+
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
336
|
+
find_next = bool(args.get("findNext", True))
|
|
337
|
+
options: dict[str, Any] = {}
|
|
338
|
+
for source, target in (
|
|
339
|
+
("allow", "allow"),
|
|
340
|
+
("deny", "deny"),
|
|
341
|
+
("allowDomains", "allow_domains"),
|
|
342
|
+
("denyDomains", "deny_domains"),
|
|
343
|
+
("restrictCss", "restrict_css"),
|
|
344
|
+
("restrictXpath", "restrict_xpath"),
|
|
345
|
+
("tags", "tags"),
|
|
346
|
+
("attrs", "attrs"),
|
|
347
|
+
("denyExtensions", "deny_extensions"),
|
|
348
|
+
):
|
|
349
|
+
value = args.get(source)
|
|
350
|
+
if value is not None:
|
|
351
|
+
options[target] = value
|
|
352
|
+
for source, target in (
|
|
353
|
+
("canonicalize", "canonicalize"),
|
|
354
|
+
("strip", "strip"),
|
|
355
|
+
("keepFragment", "keep_fragment"),
|
|
356
|
+
):
|
|
357
|
+
value = args.get(source)
|
|
358
|
+
if isinstance(value, bool):
|
|
359
|
+
options[target] = value
|
|
360
|
+
try:
|
|
361
|
+
extractor = LinkExtractor(**options)
|
|
362
|
+
except Exception as error:
|
|
363
|
+
raise ValueError(f"invalid link rule: {error}") from error
|
|
364
|
+
# 上游把注解写成 Response,实际只读 .url 与 .css;Selector 已在 V11 实测可用。
|
|
365
|
+
urls = list(extractor.extract(cast(Any, page)))
|
|
366
|
+
truncated = len(urls) > limit
|
|
367
|
+
kept = urls[:limit]
|
|
368
|
+
candidates: list[dict[str, str]] = []
|
|
369
|
+
seen: set[str] = set()
|
|
370
|
+
if find_next:
|
|
371
|
+
for element in page.css("a, area"):
|
|
372
|
+
href = element.attrib.get("href")
|
|
373
|
+
if not href:
|
|
374
|
+
continue
|
|
375
|
+
text = str(element.get_all_text(strip=True))
|
|
376
|
+
reason = _next_reason(text, href)
|
|
377
|
+
if not reason:
|
|
378
|
+
continue
|
|
379
|
+
url = str(page.urljoin(href))
|
|
380
|
+
if url in seen:
|
|
381
|
+
continue
|
|
382
|
+
seen.add(url)
|
|
383
|
+
candidates.append({"url": url, "text": text, "reason": reason})
|
|
384
|
+
if len(candidates) >= 20:
|
|
385
|
+
break
|
|
386
|
+
return {
|
|
387
|
+
"count": len(urls),
|
|
388
|
+
"truncated": truncated,
|
|
389
|
+
"links": [{"url": url} for url in kept],
|
|
390
|
+
"nextCandidates": candidates,
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _positive_int(value: Any, field: str, default: int) -> int:
|
|
395
|
+
"""取一个正整数;非法值抛 ValueError,由 adapters 转成 BAD_ARGS。"""
|
|
396
|
+
if value is None:
|
|
397
|
+
return default
|
|
398
|
+
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
|
|
399
|
+
raise ValueError(f"{field} must be a positive integer")
|
|
400
|
+
return value
|