@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
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
annotated-types==0.8.0 --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
|
|
2
|
+
anyio==4.15.1 --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101
|
|
3
|
+
apify_fingerprint_datapoints==0.15.0 --hash=sha256:fc9299b3136880f47b468897cd00ac622ad2c2a93e9cc9f972d10dbf5ed2b3aa
|
|
4
|
+
attrs==26.1.0 --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309
|
|
5
|
+
beautifulsoup4==4.15.0 --hash=sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9
|
|
6
|
+
browserforge==1.2.4 --hash=sha256:fb1c14e62ac09de221dcfc73074200269f697596c642cb200ceaab1127a17542
|
|
7
|
+
certifi==2026.10.23 --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
|
|
8
|
+
cffi==2.1.1 --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72
|
|
9
|
+
click==8.5.0 --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360
|
|
10
|
+
cryptography==50.0.2 --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb
|
|
11
|
+
cssselect==1.6.0 --hash=sha256:6df6eab9b264c0f2092a6e386b33610e1684a25e27925ecebe25e3d97cbf3525
|
|
12
|
+
curl_cffi==0.16.3 --hash=sha256:f3b63da797912bc82911e34dfe449725514e4281527fb516931fc457087cfb44
|
|
13
|
+
greenlet==3.5.6 --hash=sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46
|
|
14
|
+
h11==0.16.0 --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
|
|
15
|
+
httpcore2==2.16.0 --hash=sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f
|
|
16
|
+
httpx2==2.16.0 --hash=sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a
|
|
17
|
+
idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
|
18
|
+
jsonschema==4.26.0 --hash=sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce
|
|
19
|
+
jsonschema-specifications==2025.9.1 --hash=sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe
|
|
20
|
+
lxml==6.1.3 --hash=sha256:2bec13085dc8ef48a3fe62f7dfcacfeda2c785cdf19cc8eeda2bb9ed081da165
|
|
21
|
+
markdownify==1.2.3 --hash=sha256:a189a0bedfd14009030fde5f85bb6f77c56897cb839b5c25315dd7d4e3e290ba
|
|
22
|
+
mcp==2.3.0 --hash=sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377
|
|
23
|
+
mcp-types==2.3.0 --hash=sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d
|
|
24
|
+
msgspec==0.22.0 --hash=sha256:dd9568695911055440d2bb7099ed9098fc181d335daa772d0eb3fe8f31ba4efb
|
|
25
|
+
opentelemetry-api==1.45.1 --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb
|
|
26
|
+
orjson==3.13.0 --hash=sha256:91d933e668ff0ffe164d7c2daec36beba6d1ce7fadb71538fbe142a71f8a1e6e
|
|
27
|
+
patchright==1.64.2 --hash=sha256:c36a071c259f6e99f5b69ec5a2c4993ea3c274b04d324eed914e5937b0d7c218
|
|
28
|
+
playwright==1.64.1 --hash=sha256:59f7b041284ce8d1b72098ae50ca48a2d83692eec25154ab5ba79d4b6b4fe8a9
|
|
29
|
+
protego==0.7.0 --hash=sha256:944638aaee608f6c83fcad442695f3f9381a60be8d5007248f46b00f201fa5fc
|
|
30
|
+
pycparser==3.12 --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e
|
|
31
|
+
pydantic==2.14.1 --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454
|
|
32
|
+
pydantic-core==2.50.1 --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9
|
|
33
|
+
pyee==14.0.0 --hash=sha256:3ac2d3229a9677f7de2c33d7f52fe25b638a46b19c413fea2edc8c6d0a644e4d
|
|
34
|
+
pyjwt==2.15.1 --hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193
|
|
35
|
+
python-multipart==0.0.32 --hash=sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23
|
|
36
|
+
redis==8.1.0 --hash=sha256:a4fe1aac3d3b3cc791d4b3d5931c5a956045dc951ee74d1c913ee3ac4d2ee9fb
|
|
37
|
+
referencing==0.37.0 --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231
|
|
38
|
+
rpds-py==2026.9.1 --hash=sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35
|
|
39
|
+
scrapling==0.5 --hash=sha256:366f0ec9f1e7e998900e6c5e3a4063ea34062326394ced64e5c389b690572726
|
|
40
|
+
six==1.17.0 --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274
|
|
41
|
+
soupsieve==3.0.4 --hash=sha256:8412826614f9c632227067d0985aeb9f584bd15efc852955430e097a9fe7afbf
|
|
42
|
+
sse-starlette==3.6.0 --hash=sha256:e4dfa4d237d2712cb2b4d4918eda9b457cd6b44bbecdc838af75de836565bafd
|
|
43
|
+
starlette==1.10.0 --hash=sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4
|
|
44
|
+
tld==0.13.2 --hash=sha256:9b8fdbdb880e7ba65b216a4937f2c94c49a7226723783d5838fc958ac76f4e0c
|
|
45
|
+
truststore==0.10.5 --hash=sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c
|
|
46
|
+
typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
|
47
|
+
typing-inspection==0.4.4 --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147
|
|
48
|
+
uvicorn==0.54.0 --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf
|
|
49
|
+
w3lib==2.5.0 --hash=sha256:136fd5edfe64b53b8579838e2a7e803495bbbe6b69ddfaeed3c29a794b44f6ba
|
package/py/search.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""检索层:Tavily / Bing / Brave / Serper / DuckDuckGo / SearXNG 六条发现路径。
|
|
2
|
+
|
|
3
|
+
Scrapling 本身不是搜索引擎;这里只负责拿 URL 列表,正文渲染仍由 Host 侧的
|
|
4
|
+
search provider 交给本 sidecar 的 fetch/render。每条后端都按各家**文档里的**
|
|
5
|
+
请求与响应形状实现;真实端点与真实 key 的行为未在本机验证,夹具只钉形状与错误面。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
DEFAULT_TAVILY_ENDPOINT = "https://api.tavily.com/search"
|
|
13
|
+
DEFAULT_BING_ENDPOINT = "https://www.bing.com/search"
|
|
14
|
+
DEFAULT_BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
|
|
15
|
+
DEFAULT_SERPER_ENDPOINT = "https://google.serper.dev/search"
|
|
16
|
+
DEFAULT_DUCKDUCKGO_ENDPOINT = "https://html.duckduckgo.com/html/"
|
|
17
|
+
BACKENDS = ("auto", "tavily", "bing", "brave", "serper", "duckduckgo", "searxng")
|
|
18
|
+
DEFAULT_SEARCH_RESULTS = 8
|
|
19
|
+
DEFAULT_SEARCH_TIMEOUT_SECONDS = 30.0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SearchError(ValueError):
|
|
23
|
+
"""带机器可读错误码的检索失败。"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, code: str, message: str) -> None:
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.code = code
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _positive_int(value: Any, field: str, default: int) -> int:
|
|
31
|
+
if value is None:
|
|
32
|
+
return default
|
|
33
|
+
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
|
|
34
|
+
raise SearchError("BAD_ARGS", f"{field} must be a positive integer")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _timeout(value: Any) -> float:
|
|
39
|
+
if value is None:
|
|
40
|
+
return DEFAULT_SEARCH_TIMEOUT_SECONDS
|
|
41
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool) or value <= 0:
|
|
42
|
+
raise SearchError("BAD_ARGS", "timeoutSeconds must be a positive number")
|
|
43
|
+
return float(value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _endpoint(value: Any, default: str, field: str) -> str:
|
|
47
|
+
if value is None:
|
|
48
|
+
return default
|
|
49
|
+
if not isinstance(value, str) or not value:
|
|
50
|
+
raise SearchError("BAD_ARGS", f"{field} must be a non-empty string")
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _status_error(status: int, backend: str) -> SearchError | None:
|
|
55
|
+
if status in (401, 403):
|
|
56
|
+
return SearchError(
|
|
57
|
+
"SEARCH_AUTH",
|
|
58
|
+
f"{backend} rejected the credentials; check the configured API key",
|
|
59
|
+
)
|
|
60
|
+
if status == 429:
|
|
61
|
+
return SearchError("SEARCH_RATE_LIMIT", f"{backend} rate limit reached")
|
|
62
|
+
if status >= 400:
|
|
63
|
+
return SearchError("SEARCH_FAILED", f"{backend} answered HTTP {status}")
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
68
|
+
key = args.get("apiKey")
|
|
69
|
+
if not isinstance(key, str) or not key:
|
|
70
|
+
raise SearchError(
|
|
71
|
+
"SEARCH_AUTH",
|
|
72
|
+
"tavily needs an API key; configure tavilyApiKey or switch searchBackend to bing",
|
|
73
|
+
)
|
|
74
|
+
endpoint = _endpoint(args.get("apiEndpoint"), DEFAULT_TAVILY_ENDPOINT, "apiEndpoint")
|
|
75
|
+
from scrapling.fetchers import Fetcher
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
response = Fetcher.post(
|
|
79
|
+
endpoint,
|
|
80
|
+
json={
|
|
81
|
+
"api_key": key,
|
|
82
|
+
"query": query,
|
|
83
|
+
"max_results": limit,
|
|
84
|
+
"search_depth": "basic",
|
|
85
|
+
},
|
|
86
|
+
timeout=timeout,
|
|
87
|
+
)
|
|
88
|
+
except Exception as error: # noqa: BLE001 —— 只翻译成带码的失败,不回显请求体
|
|
89
|
+
raise _translate(error, "tavily") from None
|
|
90
|
+
failed = _status_error(int(getattr(response, "status", 0)), "tavily")
|
|
91
|
+
if failed is not None:
|
|
92
|
+
raise failed
|
|
93
|
+
try:
|
|
94
|
+
payload = response.json()
|
|
95
|
+
except Exception as error:
|
|
96
|
+
raise SearchError("SEARCH_FAILED", "tavily answered with invalid JSON") from error
|
|
97
|
+
results = payload.get("results") if isinstance(payload, dict) else None
|
|
98
|
+
hits: list[dict[str, str]] = []
|
|
99
|
+
if isinstance(results, list):
|
|
100
|
+
for item in results[:limit]:
|
|
101
|
+
if not isinstance(item, dict):
|
|
102
|
+
continue
|
|
103
|
+
url = item.get("url")
|
|
104
|
+
if not isinstance(url, str) or not url:
|
|
105
|
+
continue
|
|
106
|
+
title = item.get("title")
|
|
107
|
+
content = item.get("content")
|
|
108
|
+
hits.append(
|
|
109
|
+
{
|
|
110
|
+
"url": url,
|
|
111
|
+
"title": title if isinstance(title, str) else "",
|
|
112
|
+
"snippet": content if isinstance(content, str) else "",
|
|
113
|
+
}
|
|
114
|
+
)
|
|
115
|
+
return {"backend": "tavily", "hits": hits}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _bing(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
119
|
+
endpoint = _endpoint(args.get("bingEndpoint"), DEFAULT_BING_ENDPOINT, "bingEndpoint")
|
|
120
|
+
from scrapling.fetchers import Fetcher
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout)
|
|
124
|
+
except Exception as error: # noqa: BLE001
|
|
125
|
+
raise _translate(error, "bing") from None
|
|
126
|
+
failed = _status_error(int(getattr(response, "status", 0)), "bing")
|
|
127
|
+
if failed is not None:
|
|
128
|
+
raise failed
|
|
129
|
+
|
|
130
|
+
from scrapling import Selector
|
|
131
|
+
|
|
132
|
+
page = Selector(content=response.html_content)
|
|
133
|
+
hits: list[dict[str, str]] = []
|
|
134
|
+
for node in page.css("li.b_algo"):
|
|
135
|
+
link = node.css("h2 a").first
|
|
136
|
+
if link is None:
|
|
137
|
+
continue
|
|
138
|
+
href = link.attrib.get("href")
|
|
139
|
+
if not isinstance(href, str) or not href:
|
|
140
|
+
continue
|
|
141
|
+
snippet_node = node.css(".b_caption p").first or node.css("p").first
|
|
142
|
+
hits.append(
|
|
143
|
+
{
|
|
144
|
+
"url": href,
|
|
145
|
+
"title": link.get_all_text(strip=True),
|
|
146
|
+
"snippet": snippet_node.get_all_text(strip=True) if snippet_node is not None else "",
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
if len(hits) >= limit:
|
|
150
|
+
break
|
|
151
|
+
result: dict[str, Any] = {"backend": "bing", "hits": hits}
|
|
152
|
+
if not hits:
|
|
153
|
+
result["note"] = "bing returned no li.b_algo results; the page layout may have changed"
|
|
154
|
+
return result
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _require_key(args: dict[str, Any], backend: str) -> str:
|
|
158
|
+
"""取这条后端的 API key;缺了就报 `SEARCH_AUTH` 并点名该配哪一个设置。"""
|
|
159
|
+
key = args.get("apiKey")
|
|
160
|
+
if not isinstance(key, str) or not key:
|
|
161
|
+
raise SearchError(
|
|
162
|
+
"SEARCH_AUTH",
|
|
163
|
+
f"{backend} needs an API key; configure the matching key setting or switch searchBackend",
|
|
164
|
+
)
|
|
165
|
+
return key
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _json_body(response: Any, backend: str) -> dict[str, Any]:
|
|
169
|
+
"""读回一份 JSON 对象;解析不了就是这条后端的失败,不是空结果。"""
|
|
170
|
+
try:
|
|
171
|
+
payload = response.json()
|
|
172
|
+
except Exception as error: # 各家解析器的异常类型不同
|
|
173
|
+
raise SearchError("SEARCH_FAILED", f"{backend} answered with invalid JSON") from error
|
|
174
|
+
if not isinstance(payload, dict):
|
|
175
|
+
raise SearchError("SEARCH_FAILED", f"{backend} answered with a non-object JSON body")
|
|
176
|
+
return payload
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _collect(
|
|
180
|
+
items: Any,
|
|
181
|
+
*,
|
|
182
|
+
limit: int,
|
|
183
|
+
url_key: str,
|
|
184
|
+
title_key: str,
|
|
185
|
+
snippet_key: str,
|
|
186
|
+
) -> list[dict[str, str]]:
|
|
187
|
+
"""把各家形状不同的结果表收成同一份 hits(url/title/snippet)。"""
|
|
188
|
+
hits: list[dict[str, str]] = []
|
|
189
|
+
if not isinstance(items, list):
|
|
190
|
+
return hits
|
|
191
|
+
for item in items:
|
|
192
|
+
if not isinstance(item, dict):
|
|
193
|
+
continue
|
|
194
|
+
url = item.get(url_key)
|
|
195
|
+
if not isinstance(url, str) or not url:
|
|
196
|
+
continue
|
|
197
|
+
title = item.get(title_key)
|
|
198
|
+
snippet = item.get(snippet_key)
|
|
199
|
+
hits.append(
|
|
200
|
+
{
|
|
201
|
+
"url": url,
|
|
202
|
+
"title": title if isinstance(title, str) else "",
|
|
203
|
+
"snippet": snippet if isinstance(snippet, str) else "",
|
|
204
|
+
}
|
|
205
|
+
)
|
|
206
|
+
if len(hits) >= limit:
|
|
207
|
+
break
|
|
208
|
+
return hits
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _nested(payload: dict[str, Any], *keys: str) -> Any:
|
|
212
|
+
"""按路径取一层嵌套对象;中间不是对象就给 None。"""
|
|
213
|
+
current: Any = payload
|
|
214
|
+
for key in keys:
|
|
215
|
+
if not isinstance(current, dict):
|
|
216
|
+
return None
|
|
217
|
+
current = current.get(key)
|
|
218
|
+
return current
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
222
|
+
key = _require_key(args, "brave")
|
|
223
|
+
endpoint = _endpoint(args.get("braveEndpoint"), DEFAULT_BRAVE_ENDPOINT, "braveEndpoint")
|
|
224
|
+
from scrapling.fetchers import Fetcher
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
response = Fetcher.get(
|
|
228
|
+
endpoint,
|
|
229
|
+
params={"q": query, "count": limit},
|
|
230
|
+
headers={"X-Subscription-Token": key, "Accept": "application/json"},
|
|
231
|
+
timeout=timeout,
|
|
232
|
+
)
|
|
233
|
+
except Exception as error: # noqa: BLE001
|
|
234
|
+
raise _translate(error, "brave") from None
|
|
235
|
+
failed = _status_error(int(getattr(response, "status", 0)), "brave")
|
|
236
|
+
if failed is not None:
|
|
237
|
+
raise failed
|
|
238
|
+
payload = _json_body(response, "brave")
|
|
239
|
+
hits = _collect(
|
|
240
|
+
_nested(payload, "web", "results"),
|
|
241
|
+
limit=limit,
|
|
242
|
+
url_key="url",
|
|
243
|
+
title_key="title",
|
|
244
|
+
snippet_key="description",
|
|
245
|
+
)
|
|
246
|
+
return {"backend": "brave", "hits": hits}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
250
|
+
key = _require_key(args, "serper")
|
|
251
|
+
endpoint = _endpoint(args.get("serperEndpoint"), DEFAULT_SERPER_ENDPOINT, "serperEndpoint")
|
|
252
|
+
from scrapling.fetchers import Fetcher
|
|
253
|
+
|
|
254
|
+
try:
|
|
255
|
+
response = Fetcher.post(
|
|
256
|
+
endpoint,
|
|
257
|
+
json={"q": query, "num": limit},
|
|
258
|
+
headers={"X-API-KEY": key, "Content-Type": "application/json"},
|
|
259
|
+
timeout=timeout,
|
|
260
|
+
)
|
|
261
|
+
except Exception as error: # noqa: BLE001
|
|
262
|
+
raise _translate(error, "serper") from None
|
|
263
|
+
failed = _status_error(int(getattr(response, "status", 0)), "serper")
|
|
264
|
+
if failed is not None:
|
|
265
|
+
raise failed
|
|
266
|
+
payload = _json_body(response, "serper")
|
|
267
|
+
hits = _collect(
|
|
268
|
+
payload.get("organic"),
|
|
269
|
+
limit=limit,
|
|
270
|
+
url_key="link",
|
|
271
|
+
title_key="title",
|
|
272
|
+
snippet_key="snippet",
|
|
273
|
+
)
|
|
274
|
+
return {"backend": "serper", "hits": hits}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _duckduckgo_target(href: str) -> str:
|
|
278
|
+
"""DuckDuckGo 的结果链接是 `/l/?uddg=<enc>` 跳板;取出真正的目标。"""
|
|
279
|
+
from urllib.parse import parse_qs, urlparse, urlunparse
|
|
280
|
+
|
|
281
|
+
parts = urlparse(href if "://" in href else f"https:{href}" if href.startswith("//") else href)
|
|
282
|
+
if "duckduckgo.com" in parts.netloc and parts.path.startswith("/l/"):
|
|
283
|
+
target = parse_qs(parts.query).get("uddg")
|
|
284
|
+
if target:
|
|
285
|
+
return target[0]
|
|
286
|
+
return urlunparse(parts)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
290
|
+
endpoint = _endpoint(args.get("duckduckgoEndpoint"), DEFAULT_DUCKDUCKGO_ENDPOINT, "duckduckgoEndpoint")
|
|
291
|
+
from scrapling.fetchers import Fetcher
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout)
|
|
295
|
+
except Exception as error: # noqa: BLE001
|
|
296
|
+
raise _translate(error, "duckduckgo") from None
|
|
297
|
+
failed = _status_error(int(getattr(response, "status", 0)), "duckduckgo")
|
|
298
|
+
if failed is not None:
|
|
299
|
+
raise failed
|
|
300
|
+
|
|
301
|
+
from scrapling import Selector
|
|
302
|
+
|
|
303
|
+
page = Selector(content=response.html_content)
|
|
304
|
+
hits: list[dict[str, str]] = []
|
|
305
|
+
for node in page.css("div.result"):
|
|
306
|
+
link = node.css("a.result__a").first
|
|
307
|
+
if link is None:
|
|
308
|
+
continue
|
|
309
|
+
href = link.attrib.get("href")
|
|
310
|
+
if not isinstance(href, str) or not href:
|
|
311
|
+
continue
|
|
312
|
+
snippet_node = node.css(".result__snippet").first
|
|
313
|
+
hits.append(
|
|
314
|
+
{
|
|
315
|
+
"url": _duckduckgo_target(href),
|
|
316
|
+
"title": link.get_all_text(strip=True),
|
|
317
|
+
"snippet": snippet_node.get_all_text(strip=True) if snippet_node is not None else "",
|
|
318
|
+
}
|
|
319
|
+
)
|
|
320
|
+
if len(hits) >= limit:
|
|
321
|
+
break
|
|
322
|
+
result: dict[str, Any] = {"backend": "duckduckgo", "hits": hits}
|
|
323
|
+
if not hits:
|
|
324
|
+
result["note"] = "duckduckgo returned no div.result entries; it may be showing a captcha"
|
|
325
|
+
return result
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
|
|
329
|
+
endpoint = args.get("searxngEndpoint")
|
|
330
|
+
if not isinstance(endpoint, str) or not endpoint:
|
|
331
|
+
raise SearchError(
|
|
332
|
+
"SEARCH_AUTH",
|
|
333
|
+
"searxng needs an instance URL; configure searxngEndpoint or switch searchBackend",
|
|
334
|
+
)
|
|
335
|
+
base = endpoint.rstrip("/")
|
|
336
|
+
url = base if base.endswith("/search") else f"{base}/search"
|
|
337
|
+
from scrapling.fetchers import Fetcher
|
|
338
|
+
|
|
339
|
+
try:
|
|
340
|
+
response = Fetcher.get(url, params={"q": query, "format": "json"}, timeout=timeout)
|
|
341
|
+
except Exception as error: # noqa: BLE001
|
|
342
|
+
raise _translate(error, "searxng") from None
|
|
343
|
+
failed = _status_error(int(getattr(response, "status", 0)), "searxng")
|
|
344
|
+
if failed is not None:
|
|
345
|
+
raise failed
|
|
346
|
+
payload = _json_body(response, "searxng")
|
|
347
|
+
hits = _collect(
|
|
348
|
+
payload.get("results"),
|
|
349
|
+
limit=limit,
|
|
350
|
+
url_key="url",
|
|
351
|
+
title_key="title",
|
|
352
|
+
snippet_key="content",
|
|
353
|
+
)
|
|
354
|
+
return {"backend": "searxng", "hits": hits}
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _translate(error: Exception, backend: str) -> SearchError:
|
|
358
|
+
name = type(error).__name__.lower()
|
|
359
|
+
text = str(error).lower()
|
|
360
|
+
if "timeout" in name or "timed out" in text or "timeout" in text:
|
|
361
|
+
return SearchError("SEARCH_TIMEOUT", f"{backend} timed out")
|
|
362
|
+
return SearchError("SEARCH_FAILED", f"{backend} request failed: {type(error).__name__}")
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
366
|
+
"""按 ``backend`` 取回一组搜索结果。"""
|
|
367
|
+
backend = args.get("backend", "auto")
|
|
368
|
+
if backend not in BACKENDS:
|
|
369
|
+
raise SearchError("BAD_ARGS", f"unknown search backend: {backend}")
|
|
370
|
+
query = args.get("query")
|
|
371
|
+
if not isinstance(query, str) or not query.strip():
|
|
372
|
+
raise SearchError("BAD_ARGS", "query must be a non-empty string")
|
|
373
|
+
limit = _positive_int(args.get("maxResults"), "maxResults", DEFAULT_SEARCH_RESULTS)
|
|
374
|
+
timeout = _timeout(args.get("timeoutSeconds"))
|
|
375
|
+
key = args.get("apiKey")
|
|
376
|
+
resolved = backend
|
|
377
|
+
if backend == "auto":
|
|
378
|
+
# spec §6.2/§6.3 + §12.1:auto 只挑「部署真的配好了的」后端。公共引擎回退
|
|
379
|
+
# (Bing)默认关闭,要部署显式打开 searchPublicFallback;否则这里必须报
|
|
380
|
+
# SEARCH_BACKEND_MISSING,而不是擅自把查询发给公共站点。
|
|
381
|
+
searxng_endpoint = args.get("searxngEndpoint")
|
|
382
|
+
searxng_ready = isinstance(searxng_endpoint, str) and bool(searxng_endpoint)
|
|
383
|
+
public_fallback = args.get("publicFallback") is True
|
|
384
|
+
if isinstance(key, str) and key:
|
|
385
|
+
resolved = "tavily"
|
|
386
|
+
elif searxng_ready:
|
|
387
|
+
resolved = "searxng"
|
|
388
|
+
elif public_fallback:
|
|
389
|
+
resolved = "bing"
|
|
390
|
+
else:
|
|
391
|
+
raise SearchError(
|
|
392
|
+
"SEARCH_BACKEND_MISSING",
|
|
393
|
+
"no search backend is configured: set a Tavily API key or a SearXNG endpoint, "
|
|
394
|
+
"or enable searchPublicFallback to allow the public Bing fallback",
|
|
395
|
+
)
|
|
396
|
+
handlers = {
|
|
397
|
+
"tavily": _tavily,
|
|
398
|
+
"bing": _bing,
|
|
399
|
+
"brave": _brave,
|
|
400
|
+
"serper": _serper,
|
|
401
|
+
"duckduckgo": _duckduckgo,
|
|
402
|
+
"searxng": _searxng,
|
|
403
|
+
}
|
|
404
|
+
return handlers[resolved](args, query.strip(), limit, timeout)
|