@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
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 容错 HTML 解析器(纯 Node 内置实现,零外部依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 目的:为 ctx.scrapling.parse() / 选择器引擎提供文档树。
|
|
5
|
+
* 仓库约定不引入 cheerio/jsdom 等依赖,因此这里实现一个
|
|
6
|
+
* 「HTML5 子集 + 常见畸形容错」的单遍解析器:
|
|
7
|
+
*
|
|
8
|
+
* - void 元素(br/img/input…)不进栈;
|
|
9
|
+
* - script/style/textarea/title 按 raw text 处理;
|
|
10
|
+
* - li/p/td/tr/dt/dd/option 等按隐式闭合规则自动补闭;
|
|
11
|
+
* - 孤立结束标签、未闭合标签、属性引号缺失、大小写混杂均可容忍;
|
|
12
|
+
* - 文本与属性值做实体解码(常用命名实体 + 数字实体)。
|
|
13
|
+
*
|
|
14
|
+
* 节点形状(普通对象,便于序列化与遍历):
|
|
15
|
+
* 元素 { tag, attrs, children, parent, sourceSpan? }
|
|
16
|
+
* 文本 { tag: '#text', text, parent }
|
|
17
|
+
* 注释 { tag: '#comment', text, parent }
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const VOID_ELEMENTS = new Set([
|
|
21
|
+
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
|
22
|
+
'link', 'meta', 'param', 'source', 'track', 'wbr',
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
/** raw text 元素:内容直到对应结束标签,不做标签解析。 */
|
|
26
|
+
const RAWTEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title'])
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 隐式闭合表:遇到 key 开始标签时,栈顶若是 value 集合中的元素则自动弹出。
|
|
30
|
+
* 覆盖真实页面最常见的嵌套错误(li 未闭、td 未闭、p 套 p 等)。
|
|
31
|
+
*/
|
|
32
|
+
const IMPLICIT_CLOSES = {
|
|
33
|
+
li: new Set(['li']),
|
|
34
|
+
p: new Set(['p']),
|
|
35
|
+
dt: new Set(['dt', 'dd']),
|
|
36
|
+
dd: new Set(['dt', 'dd']),
|
|
37
|
+
td: new Set(['td', 'th']),
|
|
38
|
+
th: new Set(['td', 'th']),
|
|
39
|
+
tr: new Set(['tr', 'td', 'th']),
|
|
40
|
+
thead: new Set(['thead', 'tbody', 'tfoot', 'tr', 'td', 'th']),
|
|
41
|
+
tbody: new Set(['thead', 'tbody', 'tfoot', 'tr', 'td', 'th']),
|
|
42
|
+
tfoot: new Set(['thead', 'tbody', 'tfoot', 'tr', 'td', 'th']),
|
|
43
|
+
option: new Set(['option']),
|
|
44
|
+
optgroup: new Set(['option', 'optgroup']),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 块级元素开始时会隐式闭合未关闭的 <p>(HTML5 规范子集)。 */
|
|
48
|
+
const P_CLOSERS = new Set([
|
|
49
|
+
'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl',
|
|
50
|
+
'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3',
|
|
51
|
+
'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol',
|
|
52
|
+
'p', 'pre', 'section', 'table', 'ul',
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 文档树最大深度(对齐浏览器的 512 层上限)。
|
|
57
|
+
* 超过上限的新元素拍平为第 512 层祖先的子节点(浏览器同款行为),
|
|
58
|
+
* 同时保护下游所有递归遍历器不会栈溢出。
|
|
59
|
+
*/
|
|
60
|
+
const MAX_TREE_DEPTH = 512
|
|
61
|
+
|
|
62
|
+
/** 常用命名实体(够覆盖真实页面 95%+ 的情况,其余按字面量保留)。 */
|
|
63
|
+
const NAMED_ENTITIES = {
|
|
64
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0',
|
|
65
|
+
hellip: '…', mdash: '—', ndash: '–', lsquo: '\u2018', rsquo: '\u2019',
|
|
66
|
+
ldquo: '\u201c', rdquo: '\u201d', copy: '©', reg: '®', trade: '™',
|
|
67
|
+
deg: '°', middot: '·', laquo: '«', raquo: '»', times: '×', divide: '÷',
|
|
68
|
+
plusmn: '±', para: '¶', sect: '§', bull: '•', dagger: '†', euro: '€',
|
|
69
|
+
pound: '£', yen: '¥', cent: '¢', frac12: '½', frac14: '¼', frac34: '¾',
|
|
70
|
+
sup2: '²', sup3: '³', micro: 'µ', shy: '\u00ad', ensp: '\u2002', emsp: '\u2003',
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const ENTITY_RE = /&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});?/g
|
|
74
|
+
|
|
75
|
+
/** 实体解码:命名/十进制/十六进制;无法识别时原样保留。 */
|
|
76
|
+
export function decodeEntities(input) {
|
|
77
|
+
if (!input || input.indexOf('&') < 0) return input
|
|
78
|
+
return input.replace(ENTITY_RE, (raw, body) => {
|
|
79
|
+
let replacement = null
|
|
80
|
+
if (body[0] === '#') {
|
|
81
|
+
const isHex = body[1] === 'x' || body[1] === 'X'
|
|
82
|
+
const code = Number.parseInt(body.slice(isHex ? 2 : 1), isHex ? 16 : 10)
|
|
83
|
+
if (Number.isFinite(code) && code > 0 && code <= 0x10ffff) {
|
|
84
|
+
try { replacement = String.fromCodePoint(code) } catch { replacement = null }
|
|
85
|
+
}
|
|
86
|
+
} else if (raw.endsWith(';')) {
|
|
87
|
+
replacement = NAMED_ENTITIES[body] ?? null
|
|
88
|
+
}
|
|
89
|
+
return replacement ?? raw
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const TAG_NAME_RE = /^[a-zA-Z][a-zA-Z0-9:_.-]*/
|
|
94
|
+
|
|
95
|
+
/** 解析一段 HTML,返回 #document 根节点。入口剥掉 UTF-8 BOM。 */
|
|
96
|
+
export function parseHtml(html) {
|
|
97
|
+
const input = typeof html === 'string' ? html : String(html ?? '')
|
|
98
|
+
const source = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input
|
|
99
|
+
const doc = { tag: '#document', attrs: {}, children: [], parent: null }
|
|
100
|
+
const stack = [doc]
|
|
101
|
+
const top = () => stack[stack.length - 1]
|
|
102
|
+
|
|
103
|
+
const appendNode = (node) => {
|
|
104
|
+
node.parent = top()
|
|
105
|
+
top().children.push(node)
|
|
106
|
+
}
|
|
107
|
+
const appendText = (raw, { decode = true } = {}) => {
|
|
108
|
+
if (!raw) return
|
|
109
|
+
appendNode({ tag: '#text', text: decode ? decodeEntities(raw) : raw })
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let pos = 0
|
|
113
|
+
const len = source.length
|
|
114
|
+
|
|
115
|
+
while (pos < len) {
|
|
116
|
+
const lt = source.indexOf('<', pos)
|
|
117
|
+
if (lt < 0) { appendText(source.slice(pos)); break }
|
|
118
|
+
if (lt > pos) appendText(source.slice(pos, lt))
|
|
119
|
+
|
|
120
|
+
const rest = source.slice(lt)
|
|
121
|
+
if (rest.startsWith('<!--')) {
|
|
122
|
+
const end = source.indexOf('-->', lt + 4)
|
|
123
|
+
const stop = end < 0 ? len : end + 3
|
|
124
|
+
appendNode({ tag: '#comment', text: source.slice(lt + 4, end < 0 ? len : end) })
|
|
125
|
+
pos = stop
|
|
126
|
+
continue
|
|
127
|
+
}
|
|
128
|
+
if (rest.startsWith('<!') || rest.startsWith('<?')) {
|
|
129
|
+
const end = source.indexOf('>', lt)
|
|
130
|
+
pos = end < 0 ? len : end + 1
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
if (rest.startsWith('</')) {
|
|
134
|
+
const after = lt + 2
|
|
135
|
+
const nameMatch = TAG_NAME_RE.exec(source.slice(after))
|
|
136
|
+
if (!nameMatch) {
|
|
137
|
+
// 形如 '</ >' 或 '</3':当普通文本处理
|
|
138
|
+
appendText('</')
|
|
139
|
+
pos = after
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
const name = nameMatch[0].toLowerCase()
|
|
143
|
+
const closeAt = source.indexOf('>', after)
|
|
144
|
+
pos = closeAt < 0 ? len : closeAt + 1
|
|
145
|
+
// 从栈顶向下找同名开标签;找到则弹到它为止,找不到则忽略(孤立结束标签)
|
|
146
|
+
let idx = -1
|
|
147
|
+
for (let i = stack.length - 1; i >= 1; i--) {
|
|
148
|
+
if (stack[i].tag === name) { idx = i; break }
|
|
149
|
+
}
|
|
150
|
+
if (idx > 0) stack.length = idx
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const nameMatch = TAG_NAME_RE.exec(rest.slice(1))
|
|
155
|
+
if (!nameMatch) {
|
|
156
|
+
// '<' 后不是标签名(如 "3 < 5"):按文本处理
|
|
157
|
+
appendText('<')
|
|
158
|
+
pos = lt + 1
|
|
159
|
+
continue
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const name = nameMatch[0].toLowerCase()
|
|
163
|
+
const { attrs, selfClosing, nextPos } = readTag(source, lt + 1 + nameMatch[0].length)
|
|
164
|
+
pos = nextPos
|
|
165
|
+
|
|
166
|
+
// 隐式闭合:新开始标签触发的栈顶弹出
|
|
167
|
+
const closes = IMPLICIT_CLOSES[name]
|
|
168
|
+
if (closes) {
|
|
169
|
+
while (stack.length > 1 && closes.has(top().tag)) stack.pop()
|
|
170
|
+
} else if (P_CLOSERS.has(name)) {
|
|
171
|
+
while (stack.length > 1 && top().tag === 'p') stack.pop()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const node = { tag: name, attrs, children: [], parent: null }
|
|
175
|
+
appendNode(node)
|
|
176
|
+
|
|
177
|
+
if (selfClosing || VOID_ELEMENTS.has(name)) continue
|
|
178
|
+
|
|
179
|
+
if (RAWTEXT_ELEMENTS.has(name)) {
|
|
180
|
+
const { text, nextPos: rawNext } = readRawText(source, pos, name)
|
|
181
|
+
/* raw text 直接挂到当前元素(该元素未入栈,不能用 appendNode) */
|
|
182
|
+
node.children.push({
|
|
183
|
+
tag: '#text',
|
|
184
|
+
text: name === 'script' || name === 'style' ? text : decodeEntities(text),
|
|
185
|
+
parent: node,
|
|
186
|
+
})
|
|
187
|
+
pos = rawNext
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/* 深度上限:超过 512 层不再入栈,新元素拍平为兄弟(浏览器同款行为) */
|
|
192
|
+
if (stack.length < MAX_TREE_DEPTH) stack.push(node)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return doc
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 读取开始标签的属性直到 '>',返回小写属性表 / 是否自闭合 / 下一个读取位置。
|
|
200
|
+
* 容错:属性值引号可缺失,布尔属性值为空串,重复属性取首个。
|
|
201
|
+
*/
|
|
202
|
+
function readTag(source, pos) {
|
|
203
|
+
const attrs = {}
|
|
204
|
+
const len = source.length
|
|
205
|
+
let selfClosing = false
|
|
206
|
+
let i = pos
|
|
207
|
+
|
|
208
|
+
for (;;) {
|
|
209
|
+
while (i < len && /\s/.test(source[i])) i++
|
|
210
|
+
if (i >= len) return { attrs, selfClosing, nextPos: len }
|
|
211
|
+
const ch = source[i]
|
|
212
|
+
if (ch === '>') return { attrs, selfClosing, nextPos: i + 1 }
|
|
213
|
+
if (ch === '/') {
|
|
214
|
+
// "/>" → 自闭合;孤立的 '/' 当分隔符
|
|
215
|
+
if (source[i + 1] === '>') return { attrs, selfClosing: true, nextPos: i + 2 }
|
|
216
|
+
i++
|
|
217
|
+
continue
|
|
218
|
+
}
|
|
219
|
+
// 属性名
|
|
220
|
+
let start = i
|
|
221
|
+
while (i < len && !/[\s=>/]/.test(source[i])) i++
|
|
222
|
+
const attrName = source.slice(start, i).toLowerCase()
|
|
223
|
+
while (i < len && /\s/.test(source[i])) i++
|
|
224
|
+
let value = ''
|
|
225
|
+
if (source[i] === '=') {
|
|
226
|
+
i++
|
|
227
|
+
while (i < len && /\s/.test(source[i])) i++
|
|
228
|
+
const quote = source[i]
|
|
229
|
+
if (quote === '"' || quote === "'") {
|
|
230
|
+
i++
|
|
231
|
+
const valueEnd = source.indexOf(quote, i)
|
|
232
|
+
const stop = valueEnd < 0 ? len : valueEnd
|
|
233
|
+
value = source.slice(i, stop)
|
|
234
|
+
i = valueEnd < 0 ? len : valueEnd + 1
|
|
235
|
+
} else {
|
|
236
|
+
start = i
|
|
237
|
+
while (i < len && !/[\s>]/.test(source[i])) i++
|
|
238
|
+
value = source.slice(start, i)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (attrName && !(attrName in attrs)) attrs[attrName] = decodeEntities(value)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** 读取 raw text 元素内容(直到 </name,大小写不敏感),返回原文与结束位置。 */
|
|
246
|
+
function readRawText(source, pos, name) {
|
|
247
|
+
const lower = source.toLowerCase()
|
|
248
|
+
const needle = `</${name}`
|
|
249
|
+
const found = lower.indexOf(needle, pos)
|
|
250
|
+
if (found < 0) return { text: source.slice(pos), nextPos: source.length }
|
|
251
|
+
const closeAt = source.indexOf('>', found)
|
|
252
|
+
return { text: source.slice(pos, found), nextPos: closeAt < 0 ? source.length : closeAt + 1 }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 判断节点是否为元素(非文本/注释)。 */
|
|
256
|
+
export function isElement(node) {
|
|
257
|
+
return !!node && node.tag !== '#text' && node.tag !== '#comment' && node.tag !== '#document'
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 元素的父元素(跳过 #document)。 */
|
|
261
|
+
export function parentElement(node) {
|
|
262
|
+
const parent = node?.parent
|
|
263
|
+
return parent && parent.tag !== '#document' ? parent : null
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 收集文档/子树统计信息(元素数、最大深度、纯文本长度、标题)。 */
|
|
267
|
+
export function documentStats(doc) {
|
|
268
|
+
let elements = 0
|
|
269
|
+
let maxDepth = 0
|
|
270
|
+
let textLength = 0
|
|
271
|
+
let title = ''
|
|
272
|
+
const walk = (node, depth) => {
|
|
273
|
+
maxDepth = Math.max(maxDepth, depth)
|
|
274
|
+
for (const child of node.children || []) {
|
|
275
|
+
if (child.tag === '#text') { textLength += child.text.length; continue }
|
|
276
|
+
if (child.tag === '#comment') continue
|
|
277
|
+
elements++
|
|
278
|
+
if (child.tag === 'title' && !title) {
|
|
279
|
+
title = (child.children || []).filter((c) => c.tag === '#text').map((c) => c.text).join('').trim()
|
|
280
|
+
}
|
|
281
|
+
walk(child, depth + 1)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
walk(doc, 0)
|
|
285
|
+
return { elements, maxDepth, textLength, title }
|
|
286
|
+
}
|
package/lib/index.mjs
CHANGED
|
@@ -2,4 +2,7 @@
|
|
|
2
2
|
* dsh-scrapling API 导出
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
export { name, apply } from './host.mjs'
|
|
5
|
+
export { name, apply, DEFAULT_PORT } from './host.mjs'
|
|
6
|
+
export { parseHtml, documentStats, decodeEntities } from './html-parser.mjs'
|
|
7
|
+
export { createSelectorDocument, extract, SelectorError } from './selectors.mjs'
|
|
8
|
+
export { createCrawler } from './crawler.mjs'
|