@capyclaw/scrapling 1.0.2 → 1.1.0
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/README.md +123 -210
- package/client/client.js +26 -7
- package/cordis.patch.yml +8 -1
- package/demo/news.html +53 -0
- package/demo/products.html +68 -0
- package/demo/quotes.html +72 -0
- package/lib/crawler.mjs +370 -0
- package/lib/host.mjs +86 -35
- package/lib/html-parser.mjs +286 -0
- package/lib/index.mjs +4 -1
- package/lib/selectors.mjs +427 -0
- package/package.json +11 -4
- package/server/server.mjs +264 -0
- package/ui/app.js +663 -0
- package/ui/index.html +169 -0
- package/ui/style.css +241 -0
package/lib/crawler.mjs
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 爬取流水线(fetch → parse → extract),带步骤计时与历史记录。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标:让「DSH 如何爬取数据」可被观测——每一步(解析 URL/发请求/
|
|
5
|
+
* 收响应/读内容/建文档树/提取)都记录真实耗时与细节,前端按步骤回放。
|
|
6
|
+
*
|
|
7
|
+
* 诚实边界:只有 HTTP 模式;浏览器渲染(Cloudflare 绕过等)依赖外部
|
|
8
|
+
* Python scrapling 运行时,未实现,调用会返回结构化的 NOT_IMPLEMENTED。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { parseHtml, documentStats } from './html-parser.mjs'
|
|
12
|
+
import { extract as runExtract, SelectorError } from './selectors.mjs'
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_HTML_BYTES = 5 * 1024 * 1024
|
|
15
|
+
const DEFAULT_HISTORY_LIMIT = 20
|
|
16
|
+
|
|
17
|
+
/** 步骤计时器:每步记录 label/detail/ms,错误带「下一步」提示。 */
|
|
18
|
+
class StepRecorder {
|
|
19
|
+
constructor() {
|
|
20
|
+
this.steps = []
|
|
21
|
+
this.last = performance.now()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
add(id, label, { status = 'ok', detail = '', ms } = {}) {
|
|
25
|
+
const now = performance.now()
|
|
26
|
+
const step = { id, label, status, detail, ms: ms ?? Math.round((now - this.last) * 10) / 10 }
|
|
27
|
+
this.last = now
|
|
28
|
+
this.steps.push(step)
|
|
29
|
+
return step
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
total() {
|
|
33
|
+
return Math.round(this.steps.reduce((sum, s) => sum + (s.ms || 0), 0) * 10) / 10
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** HTML meta 声明 charset 的嗅探(ASCII 区扫描,前 2048 字节足够)。 */
|
|
38
|
+
const META_CHARSET_RE = /<meta[^>]+charset\s*=\s*["']?\s*([-\w]+)/i
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 按「响应头 charset → BOM → meta 标签 → UTF-8」的顺序解码响应体。
|
|
42
|
+
* 大量中文老站点仍是 GBK/GB2312/GB18030,undici 的 response.text() 只会按
|
|
43
|
+
* UTF-8 解码,直接用会得到乱码——所以这里必须自己按字节解码。
|
|
44
|
+
*/
|
|
45
|
+
export function decodeBody(buffer, contentTypeHeader) {
|
|
46
|
+
const head = buffer.subarray(0, 3)
|
|
47
|
+
// BOM 优先:UTF-8 / UTF-16 LE / UTF-16 BE
|
|
48
|
+
if (head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf) {
|
|
49
|
+
return { text: decodeWith('utf-8', buffer.subarray(3)), charset: 'utf-8(bom)' }
|
|
50
|
+
}
|
|
51
|
+
if (head[0] === 0xff && head[1] === 0xfe) {
|
|
52
|
+
return { text: decodeWith('utf-16le', buffer.subarray(2)), charset: 'utf-16le(bom)' }
|
|
53
|
+
}
|
|
54
|
+
if (head[0] === 0xfe && head[1] === 0xff) {
|
|
55
|
+
return { text: decodeWith('utf-16be', buffer.subarray(2)), charset: 'utf-16be(bom)' }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let charset = null
|
|
59
|
+
// 1) Content-Type 响应头
|
|
60
|
+
if (contentTypeHeader) {
|
|
61
|
+
const m = /charset\s*=\s*["']?\s*([-\w]+)/i.exec(contentTypeHeader)
|
|
62
|
+
if (m) charset = m[1]
|
|
63
|
+
}
|
|
64
|
+
// 2) <meta charset> / <meta http-equiv content-type>(内容按 latin1 看 ASCII 结构)
|
|
65
|
+
if (!charset) {
|
|
66
|
+
const probe = buffer.subarray(0, 2048).toString('latin1')
|
|
67
|
+
const m = META_CHARSET_RE.exec(probe)
|
|
68
|
+
if (m) charset = m[1]
|
|
69
|
+
}
|
|
70
|
+
if (!charset) charset = 'utf-8'
|
|
71
|
+
|
|
72
|
+
return { text: decodeWith(charset, buffer), charset }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function decodeWith(charset, buffer) {
|
|
76
|
+
try {
|
|
77
|
+
return new TextDecoder(charset, { fatal: false }).decode(buffer)
|
|
78
|
+
} catch {
|
|
79
|
+
// Node 未带该编码的 ICU 数据等情况:退回 UTF-8 容错解码
|
|
80
|
+
try { return new TextDecoder('utf-8', { fatal: false }).decode(buffer) }
|
|
81
|
+
catch { return buffer.toString('utf8') }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 把底层网络错误翻译成普通人能懂的中文(保留原始码便于诊断)。 */
|
|
86
|
+
function describeNetworkError(error) {
|
|
87
|
+
const cause = error?.cause || {}
|
|
88
|
+
const code = cause.code || error?.code || ''
|
|
89
|
+
const raw = code || (cause.message ? String(cause.message).slice(0, 60) : String(error.message || '').slice(0, 60))
|
|
90
|
+
const table = [
|
|
91
|
+
[/ECONNREFUSED/, '目标服务器拒绝连接(端口未开放或服务未启动)'],
|
|
92
|
+
[/ENOTFOUND|EAI_AGAIN/, '域名无法解析(网址可能拼写有误,或该域名不存在)'],
|
|
93
|
+
[/ECONNRESET/, '连接被目标服务器重置'],
|
|
94
|
+
[/UND_ERR_CONNECT_TIMEOUT|ConnectTimeout/i, '连接建立超时'],
|
|
95
|
+
[/CERT|TLS/i, 'HTTPS 证书校验失败'],
|
|
96
|
+
[/EPROTO/, '协议不匹配(该端口可能不是网站服务)'],
|
|
97
|
+
]
|
|
98
|
+
for (const [pattern, message] of table) {
|
|
99
|
+
if (pattern.test(code) || pattern.test(String(cause.message || ''))) {
|
|
100
|
+
return { message: `${message}(${raw})`, raw }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { message: `无法连接到目标网址(${raw})`, raw }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 生成短 id(c1, c2, …),人眼可读、URL 友好。 */
|
|
107
|
+
function createIdFactory() {
|
|
108
|
+
let n = 0
|
|
109
|
+
return () => `c${++n}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 创建爬取器实例。
|
|
114
|
+
*
|
|
115
|
+
* @param {object} [options]
|
|
116
|
+
* @param {number} [options.timeoutMs=20000] 默认超时
|
|
117
|
+
* @param {string} [options.userAgent] 默认 UA
|
|
118
|
+
* @param {number} [options.maxHtmlBytes=5MB] 响应体大小上限
|
|
119
|
+
* @param {number} [options.historyLimit=20] 历史记录条数
|
|
120
|
+
* @param {Function} [options.fetchImpl] 可注入的 fetch(测试用)
|
|
121
|
+
*/
|
|
122
|
+
export function createCrawler(options = {}) {
|
|
123
|
+
const {
|
|
124
|
+
timeoutMs: defaultTimeout = 20000,
|
|
125
|
+
userAgent: defaultUserAgent = 'Mozilla/5.0 (compatible; dsh-scrapling/1.1; +https://github.com/Maple496/capyclaw)',
|
|
126
|
+
maxHtmlBytes = DEFAULT_MAX_HTML_BYTES,
|
|
127
|
+
historyLimit = DEFAULT_HISTORY_LIMIT,
|
|
128
|
+
fetchImpl = globalThis.fetch?.bind(globalThis),
|
|
129
|
+
} = options
|
|
130
|
+
|
|
131
|
+
if (typeof fetchImpl !== 'function') throw new Error('[dsh-scrapling] 当前运行时没有可用的 fetch')
|
|
132
|
+
|
|
133
|
+
const nextId = createIdFactory()
|
|
134
|
+
const history = new Map()
|
|
135
|
+
const counters = { total: 0, errors: 0 }
|
|
136
|
+
/* 已解析文档缓存:crawlId → { root },选择器试玩免重复解析 */
|
|
137
|
+
const parsedCache = new Map()
|
|
138
|
+
|
|
139
|
+
function summaryOf(record) {
|
|
140
|
+
return {
|
|
141
|
+
id: record.id,
|
|
142
|
+
url: record.url,
|
|
143
|
+
ts: record.ts,
|
|
144
|
+
ok: record.ok,
|
|
145
|
+
status: record.status,
|
|
146
|
+
bytes: record.bytes,
|
|
147
|
+
contentType: record.contentType,
|
|
148
|
+
title: record.title,
|
|
149
|
+
totalMs: record.totalMs,
|
|
150
|
+
itemCount: record.itemCount,
|
|
151
|
+
steps: record.steps.length,
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function remember(record) {
|
|
156
|
+
history.set(record.id, record)
|
|
157
|
+
parsedCache.set(record.id, { root: record.root })
|
|
158
|
+
while (history.size > historyLimit) {
|
|
159
|
+
const oldest = history.keys().next().value
|
|
160
|
+
history.delete(oldest)
|
|
161
|
+
parsedCache.delete(oldest)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 对已抓取的 HTML 执行选择器提取(选择器试玩/二次提取)。 */
|
|
166
|
+
function extractSelectors(root, selectors) {
|
|
167
|
+
const started = performance.now()
|
|
168
|
+
const results = {}
|
|
169
|
+
for (const item of selectors || []) {
|
|
170
|
+
const key = item.key || item.selector
|
|
171
|
+
try {
|
|
172
|
+
const values = runExtract(root, item.selector)
|
|
173
|
+
results[key] = { selector: item.selector, count: values.length, values }
|
|
174
|
+
} catch (error) {
|
|
175
|
+
results[key] = {
|
|
176
|
+
selector: item.selector,
|
|
177
|
+
count: 0,
|
|
178
|
+
values: [],
|
|
179
|
+
error: error instanceof SelectorError ? error.message : `提取失败: ${error.message}`,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return { results, ms: Math.round((performance.now() - started) * 10) / 10 }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 执行一次完整爬取。
|
|
188
|
+
*
|
|
189
|
+
* @param {object} input
|
|
190
|
+
* @param {string} input.url 目标地址(http/https)
|
|
191
|
+
* @param {'http'|'browser'} [input.mode='http'] 抓取模式
|
|
192
|
+
* @param {number} [input.timeoutMs] 超时(毫秒)
|
|
193
|
+
* @param {string} [input.userAgent] 自定义 UA
|
|
194
|
+
* @param {Array<{key:string, selector:string}>} [input.selectors] 同时提取
|
|
195
|
+
*/
|
|
196
|
+
async function crawl(input) {
|
|
197
|
+
const rec = new StepRecorder()
|
|
198
|
+
counters.total++
|
|
199
|
+
const id = nextId()
|
|
200
|
+
|
|
201
|
+
if (input.mode && input.mode !== 'http') {
|
|
202
|
+
rec.add('mode', '检查抓取模式', {
|
|
203
|
+
status: 'error',
|
|
204
|
+
detail: `浏览器渲染模式(${input.mode})未实现:依赖外部 Python scrapling 运行时。`,
|
|
205
|
+
})
|
|
206
|
+
const record = {
|
|
207
|
+
id, url: input.url, ts: Date.now(), mode: input.mode, ok: false,
|
|
208
|
+
status: 0, bytes: 0, steps: rec.steps, totalMs: rec.total(),
|
|
209
|
+
error: { code: 'NOT_IMPLEMENTED', message: '浏览器渲染模式未实现,当前仅支持 HTTP 抓取', hint: '请在界面选择「HTTP 抓取」模式重试。' },
|
|
210
|
+
}
|
|
211
|
+
counters.errors++
|
|
212
|
+
remember(record)
|
|
213
|
+
return record
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let urlObj
|
|
217
|
+
try {
|
|
218
|
+
urlObj = new URL(input.url)
|
|
219
|
+
if (urlObj.protocol !== 'http:' && urlObj.protocol !== 'https:') {
|
|
220
|
+
throw new Error(`仅支持 http/https,当前是 ${urlObj.protocol}`)
|
|
221
|
+
}
|
|
222
|
+
rec.add('url', '解析目标网址', { detail: `${urlObj.host}${urlObj.pathname === '/' ? '' : urlObj.pathname}` })
|
|
223
|
+
} catch (error) {
|
|
224
|
+
rec.add('url', '解析目标网址', {
|
|
225
|
+
status: 'error',
|
|
226
|
+
detail: `网址无效:${error.message}`,
|
|
227
|
+
})
|
|
228
|
+
const record = {
|
|
229
|
+
id, url: String(input.url || ''), ts: Date.now(), mode: 'http', ok: false,
|
|
230
|
+
status: 0, bytes: 0, steps: rec.steps, totalMs: rec.total(),
|
|
231
|
+
error: { code: 'URL_INVALID', message: `网址无效:${error.message}`, hint: '请检查网址拼写,需要以 http:// 或 https:// 开头。' },
|
|
232
|
+
}
|
|
233
|
+
counters.errors++
|
|
234
|
+
remember(record)
|
|
235
|
+
return record
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const timeout = Number(input.timeoutMs) || defaultTimeout
|
|
239
|
+
const userAgent = input.userAgent || defaultUserAgent
|
|
240
|
+
|
|
241
|
+
let response
|
|
242
|
+
try {
|
|
243
|
+
const timeoutLabel = timeout >= 1000 ? `${(timeout / 1000).toFixed(timeout % 1000 ? 1 : 0)} 秒` : `${timeout}ms`
|
|
244
|
+
rec.add('request', '发送 HTTP 请求', { detail: `GET · 超时 ${timeoutLabel} · UA ${userAgent.slice(0, 40)}…` })
|
|
245
|
+
response = await fetchImpl(urlObj.href, {
|
|
246
|
+
headers: { 'user-agent': userAgent, accept: 'text/html,application/xhtml+xml,*/*;q=0.8' },
|
|
247
|
+
redirect: 'follow',
|
|
248
|
+
signal: AbortSignal.timeout(timeout),
|
|
249
|
+
})
|
|
250
|
+
} catch (error) {
|
|
251
|
+
const isTimeout = error.name === 'TimeoutError' || error.name === 'AbortError'
|
|
252
|
+
const described = describeNetworkError(error)
|
|
253
|
+
const message = isTimeout ? `请求超时(${timeout}ms)` : described.message
|
|
254
|
+
const timeoutLabel2 = timeout >= 1000 ? `${(timeout / 1000).toFixed(timeout % 1000 ? 1 : 0)} 秒` : `${timeout}ms`
|
|
255
|
+
rec.add('response', '等待服务器响应', {
|
|
256
|
+
status: 'error',
|
|
257
|
+
detail: isTimeout ? `请求超时(${timeoutLabel2})` : message,
|
|
258
|
+
})
|
|
259
|
+
const record = {
|
|
260
|
+
id, url: urlObj.href, ts: Date.now(), mode: 'http', ok: false,
|
|
261
|
+
status: 0, bytes: 0, steps: rec.steps, totalMs: rec.total(),
|
|
262
|
+
error: {
|
|
263
|
+
code: isTimeout ? 'TIMEOUT' : 'NETWORK',
|
|
264
|
+
message: isTimeout ? `请求超时(${timeoutLabel2})` : message,
|
|
265
|
+
hint: isTimeout
|
|
266
|
+
? '可在「高级选项」里加大超时时间后重试;也可先在浏览器里确认该网址能正常打开。'
|
|
267
|
+
: '请确认网址是否正确、网络是否可用;若是内网地址请确认服务已启动。',
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
counters.errors++
|
|
271
|
+
remember(record)
|
|
272
|
+
return record
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const contentType = response.headers.get('content-type') || ''
|
|
276
|
+
rec.add('response', '收到响应', {
|
|
277
|
+
status: response.ok ? 'ok' : 'warn',
|
|
278
|
+
detail: `HTTP ${response.status} ${response.statusText || ''} · ${contentType.split(';')[0] || '未知类型'}${response.redirected ? ' · 已跟随重定向' : ''}`,
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
let html = ''
|
|
282
|
+
let bodyBytes = 0
|
|
283
|
+
try {
|
|
284
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
285
|
+
const bytes = buffer.length
|
|
286
|
+
bodyBytes = bytes
|
|
287
|
+
if (bytes > maxHtmlBytes) {
|
|
288
|
+
rec.add('body', '读取页面内容', {
|
|
289
|
+
status: 'error',
|
|
290
|
+
detail: `页面过大:${(bytes / 1024 / 1024).toFixed(1)}MB(上限 ${(maxHtmlBytes / 1024 / 1024).toFixed(0)}MB)`,
|
|
291
|
+
})
|
|
292
|
+
const record = {
|
|
293
|
+
id, url: urlObj.href, ts: Date.now(), mode: 'http', ok: false,
|
|
294
|
+
status: response.status, bytes, steps: rec.steps, totalMs: rec.total(),
|
|
295
|
+
error: { code: 'TOO_LARGE', message: `页面内容超过大小上限(${(maxHtmlBytes / 1024 / 1024).toFixed(0)}MB)`, hint: '该页面不适合整页抓取,请选择更具体的入口页。' },
|
|
296
|
+
}
|
|
297
|
+
counters.errors++
|
|
298
|
+
remember(record)
|
|
299
|
+
return record
|
|
300
|
+
}
|
|
301
|
+
const decoded = decodeBody(buffer, response.headers.get('content-type'))
|
|
302
|
+
html = decoded.text
|
|
303
|
+
rec.add('body', '读取页面内容', { detail: `${(bytes / 1024).toFixed(1)} KB · ${decoded.charset.toUpperCase()} 解码完成` })
|
|
304
|
+
} catch (error) {
|
|
305
|
+
rec.add('body', '读取页面内容', { status: 'error', detail: `读取失败: ${error.message}` })
|
|
306
|
+
const record = {
|
|
307
|
+
id, url: urlObj.href, ts: Date.now(), mode: 'http', ok: false,
|
|
308
|
+
status: response.status, bytes: 0, steps: rec.steps, totalMs: rec.total(),
|
|
309
|
+
error: { code: 'BODY_ERROR', message: `读取响应内容失败: ${error.message}`, hint: '请重试;若持续失败可能是连接被中断。' },
|
|
310
|
+
}
|
|
311
|
+
counters.errors++
|
|
312
|
+
remember(record)
|
|
313
|
+
return record
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const root = parseHtml(html)
|
|
317
|
+
const stats = documentStats(root)
|
|
318
|
+
rec.add('dom', '构建文档树', { detail: `${stats.elements} 个元素 · 最大深度 ${stats.maxDepth} · 标题「${stats.title.slice(0, 40)}」` })
|
|
319
|
+
|
|
320
|
+
let extracts = null
|
|
321
|
+
let itemCount = 0
|
|
322
|
+
if (Array.isArray(input.selectors) && input.selectors.length) {
|
|
323
|
+
const { results } = extractSelectors(root, input.selectors)
|
|
324
|
+
extracts = results
|
|
325
|
+
itemCount = Object.values(results).reduce((sum, r) => sum + r.count, 0)
|
|
326
|
+
const okCount = Object.values(results).filter((r) => !r.error).length
|
|
327
|
+
rec.add('extract', '提取结构化数据', {
|
|
328
|
+
status: okCount === 0 && input.selectors.length > 0 ? 'warn' : 'ok',
|
|
329
|
+
detail: `${input.selectors.length} 个选择器 · 命中 ${itemCount} 条数据`,
|
|
330
|
+
})
|
|
331
|
+
} else {
|
|
332
|
+
rec.add('extract', '提取结构化数据', { status: 'skip', detail: '未指定选择器,跳过(可在结果区随时试玩选择器)' })
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
rec.add('done', '完成', { detail: `全程 ${rec.total()}ms` })
|
|
336
|
+
const record = {
|
|
337
|
+
id, url: urlObj.href, finalUrl: response.url || urlObj.href, ts: Date.now(), mode: 'http',
|
|
338
|
+
ok: response.ok, status: response.status, statusText: response.statusText,
|
|
339
|
+
contentType, bytes: bodyBytes, title: stats.title, stats,
|
|
340
|
+
steps: rec.steps, totalMs: rec.total(), extracts, itemCount,
|
|
341
|
+
html, root,
|
|
342
|
+
get summary() { return summaryOf(this) },
|
|
343
|
+
}
|
|
344
|
+
delete record.error
|
|
345
|
+
remember(record)
|
|
346
|
+
return record
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** 基于历史记录二次提取(不重新请求)。 */
|
|
350
|
+
function reExtract(crawlId, selectors) {
|
|
351
|
+
const cache = parsedCache.get(crawlId)
|
|
352
|
+
if (!cache) return null
|
|
353
|
+
const { results, ms } = extractSelectors(cache.root, selectors)
|
|
354
|
+
return { results, ms }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
crawl,
|
|
359
|
+
reExtract,
|
|
360
|
+
summaryOf,
|
|
361
|
+
list: () => [...history.values()].map(summaryOf).reverse(),
|
|
362
|
+
get: (crawlId) => {
|
|
363
|
+
const record = history.get(crawlId)
|
|
364
|
+
if (!record) return null
|
|
365
|
+
const { html, root, ...rest } = record
|
|
366
|
+
return { ...rest, htmlPreview: typeof html === 'string' ? html.slice(0, 20000) : undefined }
|
|
367
|
+
},
|
|
368
|
+
counters,
|
|
369
|
+
}
|
|
370
|
+
}
|
package/lib/host.mjs
CHANGED
|
@@ -1,25 +1,41 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-scrapling 宿主半(Cordis
|
|
2
|
+
* dsh-scrapling 宿主半(Cordis 入口)。
|
|
3
3
|
*
|
|
4
4
|
* 能力边界(诚实声明):
|
|
5
|
-
* - fetch()
|
|
6
|
-
* -
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* - fetch() 已实现:Node 内置 fetch 发起 HTTP 请求,返回状态/头/正文。
|
|
6
|
+
* - parse() 已实现:纯 Node 的容错 HTML 解析 + CSS 选择器引擎
|
|
7
|
+
* (lib/html-parser.mjs / lib/selectors.mjs),支持
|
|
8
|
+
* ::text / ::attr / 组合器 / 常见伪类;xpath 未实现。
|
|
9
|
+
* - fetchWithBrowser() 未实现:浏览器渲染 / Cloudflare 绕过需要外部 Python
|
|
10
|
+
* scrapling,直接抛 NOT_IMPLEMENTED,不会伪造结果。
|
|
11
|
+
*
|
|
12
|
+
* 工作台服务(server/server.mjs):
|
|
13
|
+
* - 默认 http://127.0.0.1:39640/ ,浏览器打开即用的可视化爬取界面;
|
|
14
|
+
* - 依赖注入可选:workbench: false 可只注册 scrapling 服务不起界面;
|
|
15
|
+
* - 通过 webserver/index-inject 注入 __DSH_SCRAPLING__ 供浏览器半挂面板。
|
|
9
16
|
*
|
|
10
17
|
* 配置(resolveConfig:ctx config → 环境变量 → 默认值):
|
|
11
|
-
* enabled
|
|
12
|
-
*
|
|
13
|
-
*
|
|
18
|
+
* enabled 是否注册服务/界面 DSH_SCRAPLING_ENABLED 默认 true
|
|
19
|
+
* port 工作台端口 DSH_SCRAPLING_PORT 默认 39640
|
|
20
|
+
* host 监听地址 DSH_SCRAPLING_HOST 默认 127.0.0.1
|
|
21
|
+
* timeoutMs 单次请求超时(ms) DSH_SCRAPLING_TIMEOUT_MS 默认 20000
|
|
22
|
+
* userAgent 默认 UA DSH_SCRAPLING_USER_AGENT
|
|
23
|
+
* workbench 是否拉起界面 DSH_SCRAPLING_WORKBENCH 默认 true
|
|
14
24
|
*/
|
|
25
|
+
import path from 'node:path'
|
|
26
|
+
import { fileURLToPath } from 'node:url'
|
|
15
27
|
import { resolveConfig } from '@capyclaw/plugin-kit/config'
|
|
16
28
|
|
|
29
|
+
import { createCrawler } from './crawler.mjs'
|
|
30
|
+
import { createSelectorDocument } from './selectors.mjs'
|
|
31
|
+
|
|
17
32
|
export const name = '@capyclaw/scrapling'
|
|
33
|
+
export const DEFAULT_PORT = 39640
|
|
18
34
|
|
|
19
35
|
function notImplemented(feature) {
|
|
20
36
|
const error = new Error(
|
|
21
|
-
`[dsh-scrapling] ${feature}
|
|
22
|
-
'请使用 fetch()
|
|
37
|
+
`[dsh-scrapling] ${feature} 未实现:浏览器渲染与 XPath 依赖外部 Python scrapling 运行时。` +
|
|
38
|
+
'请使用 fetch()/parse()(HTTP 抓取 + CSS 选择器),或另行部署 scrapling 服务后通过 HTTP 调用。',
|
|
23
39
|
)
|
|
24
40
|
error.code = 'NOT_IMPLEMENTED'
|
|
25
41
|
return error
|
|
@@ -28,56 +44,91 @@ function notImplemented(feature) {
|
|
|
28
44
|
export async function apply(ctx, config = {}) {
|
|
29
45
|
const { value: cfg, issues } = resolveConfig(config, {
|
|
30
46
|
envPrefix: 'DSH_SCRAPLING',
|
|
31
|
-
defaults: {
|
|
47
|
+
defaults: {
|
|
48
|
+
enabled: true,
|
|
49
|
+
port: DEFAULT_PORT,
|
|
50
|
+
host: '127.0.0.1',
|
|
51
|
+
timeoutMs: 20000,
|
|
52
|
+
workbench: true,
|
|
53
|
+
},
|
|
32
54
|
fields: {
|
|
33
55
|
enabled: { env: 'ENABLED', type: 'boolean' },
|
|
56
|
+
port: { env: 'PORT', type: 'port' },
|
|
57
|
+
host: { env: 'HOST' },
|
|
34
58
|
timeoutMs: { env: 'TIMEOUT_MS', type: 'number' },
|
|
35
59
|
userAgent: { env: 'USER_AGENT' },
|
|
60
|
+
workbench: { env: 'WORKBENCH', type: 'boolean' },
|
|
36
61
|
},
|
|
37
62
|
})
|
|
38
|
-
|
|
39
|
-
for (const issue of issues) ctx.logger?.warn?.(`[dsh-scrapling] 配置: ${issue}`)
|
|
40
|
-
}
|
|
63
|
+
for (const issue of issues) ctx.logger?.warn?.(`[dsh-scrapling] 配置: ${issue}`)
|
|
41
64
|
|
|
42
65
|
if (!cfg.enabled) {
|
|
43
66
|
ctx.logger?.info?.('[dsh-scrapling] 已按配置禁用,不注册 scrapling 服务')
|
|
44
67
|
return
|
|
45
68
|
}
|
|
46
69
|
|
|
70
|
+
const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
71
|
+
const crawler = createCrawler({ timeoutMs: cfg.timeoutMs, userAgent: cfg.userAgent })
|
|
72
|
+
|
|
47
73
|
ctx.provide('scrapling', {
|
|
48
74
|
/** 普通 HTTP 抓取(真实实现)。 */
|
|
49
75
|
async fetch(url, options = {}) {
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
body: options.body,
|
|
57
|
-
signal: AbortSignal.timeout(Number(options.timeoutMs) || cfg.timeoutMs),
|
|
58
|
-
})
|
|
59
|
-
const html = await response.text()
|
|
60
|
-
return {
|
|
61
|
-
url,
|
|
62
|
-
status: response.status,
|
|
63
|
-
ok: response.ok,
|
|
64
|
-
headers: Object.fromEntries(response.headers.entries()),
|
|
65
|
-
html,
|
|
76
|
+
const record = await crawler.crawl({ url, timeoutMs: options.timeoutMs, userAgent: options.userAgent || options.headers?.['user-agent'] })
|
|
77
|
+
if (record.error) {
|
|
78
|
+
const error = new Error(record.error.message)
|
|
79
|
+
error.code = record.error.code
|
|
80
|
+
error.hint = record.error.hint
|
|
81
|
+
throw error
|
|
66
82
|
}
|
|
83
|
+
return { url: record.url, status: record.status, ok: record.ok, headers: {}, html: record.html }
|
|
67
84
|
},
|
|
68
85
|
|
|
69
|
-
/**
|
|
86
|
+
/** 浏览器渲染:未实现(诚实声明,不伪造结果)。 */
|
|
70
87
|
async fetchWithBrowser() {
|
|
71
88
|
throw notImplemented('fetchWithBrowser')
|
|
72
89
|
},
|
|
73
90
|
|
|
74
|
-
/**
|
|
75
|
-
parse() {
|
|
76
|
-
|
|
91
|
+
/** HTML → 文档包装:css('.a .b::text') / css('a::attr(href)')。 */
|
|
92
|
+
parse(html, options = {}) {
|
|
93
|
+
return createSelectorDocument(html, options)
|
|
77
94
|
},
|
|
95
|
+
|
|
96
|
+
/** 工作台爬取流水线(带步骤计时,工作台界面数据源)。 */
|
|
97
|
+
crawler,
|
|
78
98
|
})
|
|
79
99
|
|
|
100
|
+
/* 工作台界面(默认开启;workbench:false 可关闭) */
|
|
101
|
+
let instance = null
|
|
102
|
+
if (cfg.workbench) {
|
|
103
|
+
const { startWorkbenchServer } = await import('../server/server.mjs')
|
|
104
|
+
try {
|
|
105
|
+
instance = await startWorkbenchServer({
|
|
106
|
+
port: cfg.port,
|
|
107
|
+
host: cfg.host,
|
|
108
|
+
packageDir,
|
|
109
|
+
crawler,
|
|
110
|
+
version: '1.1.0',
|
|
111
|
+
})
|
|
112
|
+
ctx.logger?.info?.(`[dsh-scrapling] 爬虫工作台已就绪: ${instance.url}/ (浏览器打开即用)`)
|
|
113
|
+
/* 与 DSH web 客户端的桥:注入 boot 全局(launchpad/port-sidebar 同款协议) */
|
|
114
|
+
ctx.on?.('webserver/index-inject', (table) => {
|
|
115
|
+
table.push({ kind: 'global', name: '__DSH_SCRAPLING__', value: { url: `${instance.url}/`, version: '1.1.0' } })
|
|
116
|
+
})
|
|
117
|
+
} catch (error) {
|
|
118
|
+
ctx.logger?.warn?.(`[dsh-scrapling] 工作台启动失败(scrapling 服务仍可用): ${error.message}`)
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
ctx.logger?.info?.('[dsh-scrapling] workbench=false,仅注册 scrapling 服务')
|
|
122
|
+
}
|
|
123
|
+
|
|
80
124
|
ctx.logger?.info?.(
|
|
81
|
-
`[dsh-scrapling] 已注册 scrapling
|
|
125
|
+
`[dsh-scrapling] 已注册 scrapling 服务(fetch + parse;浏览器/XPath 未实现,timeout=${cfg.timeoutMs}ms)`,
|
|
82
126
|
)
|
|
127
|
+
|
|
128
|
+
return async () => {
|
|
129
|
+
if (instance) {
|
|
130
|
+
await instance.close()
|
|
131
|
+
ctx.logger?.info?.('[dsh-scrapling] 爬虫工作台已停止')
|
|
132
|
+
}
|
|
133
|
+
}
|
|
83
134
|
}
|