@capyclaw/scrapling 1.0.2 → 1.1.1
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 +124 -210
- package/client/client.js +138 -9
- package/cordis.patch.yml +10 -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 +109 -34
- package/lib/html-parser.mjs +286 -0
- package/lib/index.mjs +4 -1
- package/lib/selectors.mjs +427 -0
- package/package.json +14 -6
- package/server/server.mjs +253 -0
- package/ui/app.js +663 -0
- package/ui/index.html +169 -0
- package/ui/style.css +241 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<title>好物清单 · 演示商城</title>
|
|
6
|
+
<style>
|
|
7
|
+
body { font-family: "Microsoft YaHei", sans-serif; max-width: 900px; margin: 40px auto; color: #2c2c2c; background: #f6f7fb; }
|
|
8
|
+
h1 { color: #1f3a93; }
|
|
9
|
+
.grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
|
|
10
|
+
.product { background: #fff; border-radius: 8px; padding: 16px; box-shadow: 0 1px 4px rgba(0,0,0,.08); }
|
|
11
|
+
.product .name { font-weight: bold; font-size: 16px; }
|
|
12
|
+
.product .price { color: #c0392b; font-size: 20px; margin: 6px 0; }
|
|
13
|
+
.product .meta { color: #777; font-size: 13px; }
|
|
14
|
+
.rating { color: #e67e22; }
|
|
15
|
+
.out-of-stock .name::after { content: "(缺货)"; color: #999; }
|
|
16
|
+
table.summary { border-collapse: collapse; margin-top: 24px; width: 100%; background: #fff; }
|
|
17
|
+
table.summary th, table.summary td { border: 1px solid #ddd; padding: 6px 10px; text-align: left; font-size: 14px; }
|
|
18
|
+
</style>
|
|
19
|
+
</head>
|
|
20
|
+
<body>
|
|
21
|
+
<h1>好物清单</h1>
|
|
22
|
+
<p class="intro">内置演示商城页:练习表格与卡片两种结构的 CSS 选择器提取。</p>
|
|
23
|
+
|
|
24
|
+
<div class="grid">
|
|
25
|
+
<div class="product" data-sku="A-1001">
|
|
26
|
+
<div class="name">机械键盘 87 键</div>
|
|
27
|
+
<div class="price">¥399.00</div>
|
|
28
|
+
<div class="meta"><span class="rating" data-score="4.8">评分 4.8</span> · 月销 1200+ · <span class="stock">有货</span></div>
|
|
29
|
+
</div>
|
|
30
|
+
<div class="product out-of-stock" data-sku="A-1002">
|
|
31
|
+
<div class="name">无线静音鼠标</div>
|
|
32
|
+
<div class="price">¥129.00</div>
|
|
33
|
+
<div class="meta"><span class="rating" data-score="4.5">评分 4.5</span> · 月销 800+ · <span class="stock">缺货</span></div>
|
|
34
|
+
</div>
|
|
35
|
+
<div class="product" data-sku="A-1003">
|
|
36
|
+
<div class="name">4K 显示器 27 寸</div>
|
|
37
|
+
<div class="price">¥2199.00</div>
|
|
38
|
+
<div class="meta"><span class="rating" data-score="4.9">评分 4.9</span> · 月销 300+ · <span class="stock">有货</span></div>
|
|
39
|
+
</div>
|
|
40
|
+
<div class="product" data-sku="A-1004">
|
|
41
|
+
<div class="name">USB-C 扩展坞</div>
|
|
42
|
+
<div class="price">¥259.00</div>
|
|
43
|
+
<div class="meta"><span class="rating" data-score="4.6">评分 4.6</span> · 月销 2100+ · <span class="stock">有货</span></div>
|
|
44
|
+
</div>
|
|
45
|
+
<div class="product" data-sku="A-1005">
|
|
46
|
+
<div class="name">降噪蓝牙耳机</div>
|
|
47
|
+
<div class="price">¥799.00</div>
|
|
48
|
+
<div class="meta"><span class="rating" data-score="4.7">评分 4.7</span> · 月销 560+ · <span class="stock">有货</span></div>
|
|
49
|
+
</div>
|
|
50
|
+
<div class="product out-of-stock" data-sku="A-1006">
|
|
51
|
+
<div class="name">桌面升降支架</div>
|
|
52
|
+
<div class="price">¥459.00</div>
|
|
53
|
+
<div class="meta"><span class="rating" data-score="4.4">评分 4.4</span> · 月销 90+ · <span class="stock">缺货</span></div>
|
|
54
|
+
</div>
|
|
55
|
+
</div>
|
|
56
|
+
|
|
57
|
+
<table class="summary">
|
|
58
|
+
<thead><tr><th>商品</th><th>价格</th><th>评分</th></tr></thead>
|
|
59
|
+
<tbody>
|
|
60
|
+
<tr><td>机械键盘 87 键</td><td>399.00</td><td>4.8</td></tr>
|
|
61
|
+
<tr><td>无线静音鼠标</td><td>129.00</td><td>4.5</td></tr>
|
|
62
|
+
<tr><td>4K 显示器 27 寸</td><td>2199.00</td><td>4.9</td></tr>
|
|
63
|
+
</tbody>
|
|
64
|
+
</table>
|
|
65
|
+
|
|
66
|
+
<footer class="site-footer"><p>内置演示页 · 用于 DSH Scrapling 工作台演示</p></footer>
|
|
67
|
+
</body>
|
|
68
|
+
</html>
|
package/demo/quotes.html
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<title>每日名言 · 演示站</title>
|
|
6
|
+
<style>
|
|
7
|
+
body { font-family: "Microsoft YaHei", sans-serif; max-width: 760px; margin: 40px auto; color: #333; background: #faf8f4; }
|
|
8
|
+
h1 { border-bottom: 3px solid #e8a33d; padding-bottom: 10px; }
|
|
9
|
+
.quote { border-left: 4px solid #e8a33d; background: #fff; margin: 18px 0; padding: 14px 18px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
|
10
|
+
.quote .text { font-size: 17px; }
|
|
11
|
+
.quote .author { color: #b3541e; margin-top: 6px; }
|
|
12
|
+
.quote .tags { margin-top: 8px; }
|
|
13
|
+
.tag { display: inline-block; background: #f0e6d2; color: #7a5c1e; border-radius: 10px; padding: 1px 10px; margin-right: 6px; font-size: 13px; text-decoration: none; }
|
|
14
|
+
.pager { margin: 24px 0; }
|
|
15
|
+
</style>
|
|
16
|
+
</head>
|
|
17
|
+
<body>
|
|
18
|
+
<h1>每日名言</h1>
|
|
19
|
+
<p class="intro">这是一个内置演示页面:无需外网,用来体验 DSH 的完整爬取流程。</p>
|
|
20
|
+
|
|
21
|
+
<div class="quote-list">
|
|
22
|
+
<div class="quote" data-id="1">
|
|
23
|
+
<span class="text">生活不是等待暴风雨过去,而是学会在雨中跳舞。</span>
|
|
24
|
+
<span class="author">佚名</span>
|
|
25
|
+
<div class="tags"><a class="tag" href="/tag/生活/1">生活</a><a class="tag" href="/tag/态度/1">态度</a></div>
|
|
26
|
+
</div>
|
|
27
|
+
<div class="quote" data-id="2">
|
|
28
|
+
<span class="text">种一棵树最好的时间是十年前,其次是现在。</span>
|
|
29
|
+
<span class="author">非洲谚语</span>
|
|
30
|
+
<div class="tags"><a class="tag" href="/tag/行动/1">行动</a><a class="tag" href="/tag/时间/1">时间</a></div>
|
|
31
|
+
</div>
|
|
32
|
+
<div class="quote" data-id="3">
|
|
33
|
+
<span class="text">简单是复杂的最高境界。</span>
|
|
34
|
+
<span class="author">达·芬奇</span>
|
|
35
|
+
<div class="tags"><a class="tag" href="/tag/设计/1">设计</a><a class="tag" href="/tag/简洁/1">简洁</a></div>
|
|
36
|
+
</div>
|
|
37
|
+
<div class="quote" data-id="4">
|
|
38
|
+
<span class="text">知道为什么而活的人,便能生存。</span>
|
|
39
|
+
<span class="author">尼采</span>
|
|
40
|
+
<div class="tags"><a class="tag" href="/tag/哲学/1">哲学</a></div>
|
|
41
|
+
</div>
|
|
42
|
+
<div class="quote" data-id="5">
|
|
43
|
+
<span class="text">千里之行,始于足下。</span>
|
|
44
|
+
<span class="author">老子</span>
|
|
45
|
+
<div class="tags"><a class="tag" href="/tag/行动/1">行动</a><a class="tag" href="/tag/古典/1">古典</a></div>
|
|
46
|
+
</div>
|
|
47
|
+
<div class="quote" data-id="6">
|
|
48
|
+
<span class="text">我们必须知道,我们必将知道。</span>
|
|
49
|
+
<span class="author">希尔伯特</span>
|
|
50
|
+
<div class="tags"><a class="tag" href="/tag/数学/1">数学</a><a class="tag" href="/tag/求知/1">求知</a></div>
|
|
51
|
+
</div>
|
|
52
|
+
<div class="quote" data-id="7">
|
|
53
|
+
<span class="text">凡是过往,皆为序章。</span>
|
|
54
|
+
<span class="author">莎士比亚</span>
|
|
55
|
+
<div class="tags"><a class="tag" href="/tag/文学/1">文学</a><a class="tag" href="/tag/希望/1">希望</a></div>
|
|
56
|
+
</div>
|
|
57
|
+
<div class="quote" data-id="8">
|
|
58
|
+
<span class="text">唯一真正的错误是我们从中学不到任何东西的错误。</span>
|
|
59
|
+
<span class="author">亨利·福特</span>
|
|
60
|
+
<div class="tags"><a class="tag" href="/tag/成长/1">成长</a></div>
|
|
61
|
+
</div>
|
|
62
|
+
</div>
|
|
63
|
+
|
|
64
|
+
<nav class="pager">
|
|
65
|
+
<a class="next" href="/demo/quotes.html?page=2">下一页 →</a>
|
|
66
|
+
</nav>
|
|
67
|
+
|
|
68
|
+
<footer class="site-footer">
|
|
69
|
+
<p>内置演示页 · 结构参考 quotes.toscrape.com · 用于 DSH Scrapling 工作台演示</p>
|
|
70
|
+
</footer>
|
|
71
|
+
</body>
|
|
72
|
+
</html>
|
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
|
+
}
|