@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.
@@ -0,0 +1,427 @@
1
+ /**
2
+ * CSS 选择器引擎(Scrapy/parsel 语义子集,纯 Node 实现)。
3
+ *
4
+ * 与 ctx.scrapling.parse(html).css(selector) 配套:
5
+ * - 复合选择器:tag / * / .class / #id / [attr] / [attr=v] / [attr^=v] /
6
+ * [attr$=v] / [attr*=v] / [attr~=v] / [attr|=v]
7
+ * - 结构伪类::first-child / :last-child / :nth-child(k)(k 从 1 计)
8
+ * - 组合器:后代(空格)、子代(>)、相邻(+)
9
+ * - 末端伪元素:::text(元素内文本节点逐条返回)、::attr(name)
10
+ * - 逗号分组:命中顺序按文档序、去重
11
+ *
12
+ * 作用域语义与 parsel 对齐:wrapper.css() 在元素作用域内匹配后代,
13
+ * 元素自身可作为组合器链上的祖先参与匹配,但不会被选为结果。
14
+ *
15
+ * 能力边界(诚实声明):不支持 XPath(parse().xpath 抛 NOT_IMPLEMENTED)、
16
+ * 不支持 :not()/:has() 等复杂伪类;超出子集的需求请拆成多个简单选择器。
17
+ */
18
+
19
+ import { isElement, parseHtml } from './html-parser.mjs'
20
+
21
+ /** 解析失败时抛出的错误(HTTP 层转 400)。 */
22
+ export class SelectorError extends Error {
23
+ constructor(message) {
24
+ super(message)
25
+ this.code = 'SELECTOR_INVALID'
26
+ }
27
+ }
28
+
29
+ /** 按顶层逗号切分选择器分组(跳过 [] 与引号内的逗号)。 */
30
+ function splitTopLevel(source) {
31
+ const parts = []
32
+ let depth = 0
33
+ let quote = null
34
+ let current = ''
35
+ for (const ch of source) {
36
+ if (quote) {
37
+ current += ch
38
+ if (ch === quote) quote = null
39
+ continue
40
+ }
41
+ if (ch === '"' || ch === "'") { quote = ch; current += ch; continue }
42
+ if (ch === '[') depth++
43
+ if (ch === ']') depth = Math.max(0, depth - 1)
44
+ if (ch === ',' && depth === 0) { parts.push(current); current = ''; continue }
45
+ current += ch
46
+ }
47
+ parts.push(current)
48
+ return parts
49
+ }
50
+
51
+ /** 解析选择器字符串 → 结构化选择器列表;非法输入抛 SelectorError。 */
52
+ export function parseSelectorList(input) {
53
+ const source = String(input ?? '').trim()
54
+ if (!source) throw new SelectorError('选择器为空')
55
+ const parts = splitTopLevel(source)
56
+ return parts.map((part) => parseComplexSelector(part.trim(), source))
57
+ }
58
+
59
+ function parseComplexSelector(source, full) {
60
+ if (!source) throw new SelectorError(`选择器存在空分组: "${full}"`)
61
+ let pseudo = null
62
+ // 末端伪元素只允许出现在整个分组末尾(::attr() 空参在这里先剥掉,再由下方给出准确报错)
63
+ const pseudoMatch = /::(text|attr)\s*(?:\(\s*([-\w]*)\s*\))?\s*$/.exec(source)
64
+ if (pseudoMatch) {
65
+ if (pseudoMatch[1] === 'text') pseudo = { kind: 'text' }
66
+ else {
67
+ if (!pseudoMatch[2]) throw new SelectorError(`::attr 需要属性名,如 ::attr(href):${source}`)
68
+ pseudo = { kind: 'attr', name: pseudoMatch[2].toLowerCase() }
69
+ }
70
+ }
71
+ const body = pseudo ? source.slice(0, source.length - pseudoMatch[0].length).trim() : source
72
+ if (!body) throw new SelectorError(`选择器缺少主体: "${source}"`)
73
+
74
+ const compounds = []
75
+ const combinators = []
76
+ let i = 0
77
+ while (i < body.length) {
78
+ const { compound, next } = readCompound(body, i)
79
+ if (!compound) throw new SelectorError(`无法解析选择器(位置 ${i}): "${source}"`)
80
+ if (compounds.length) combinators.push(compound.__combinator)
81
+ delete compound.__combinator
82
+ compounds.push(compound)
83
+ i = next
84
+ }
85
+ return { compounds, combinators, pseudo, source }
86
+ }
87
+
88
+ /**
89
+ * 读取一个复合选择器;若其与前一个之间有组合器(空白/>/+),
90
+ * 记录在 compound.__combinator(首个复合选择器不使用该值)。
91
+ */
92
+ function readCompound(body, start) {
93
+ let i = start
94
+ let combinator = null
95
+ for (;;) {
96
+ while (i < body.length && /\s/.test(body[i])) i++
97
+ if (body[i] === '>' || body[i] === '+') {
98
+ if (combinator) throw new SelectorError(`连续组合器: "${body}"`)
99
+ combinator = body[i] === '>' ? 'child' : 'adjacent'
100
+ i++
101
+ continue
102
+ }
103
+ break
104
+ }
105
+ if (i >= body.length) {
106
+ if (combinator) throw new SelectorError(`选择器以组合器结尾: "${body}"`)
107
+ return { compound: null, next: i }
108
+ }
109
+ if (!combinator && i > start && /\s/.test(body[start])) combinator = 'descendant'
110
+
111
+ const compound = {
112
+ tag: '*', classes: [], id: null, attrs: [], pseudoClasses: [],
113
+ __combinator: combinator || 'descendant',
114
+ }
115
+ /* 标识符允许非 ASCII(中文站点类名/ID 常见),与 CSS 标识符规则对齐。 */
116
+ const IDENT = '[-\\w\\u00a0-\\uffff]'
117
+ const tagMatch = new RegExp(`^[a-zA-Z]${IDENT}*`).exec(body.slice(i))
118
+ if (tagMatch) {
119
+ compound.tag = tagMatch[0].toLowerCase()
120
+ i += tagMatch[0].length
121
+ } else if (body[i] === '*') {
122
+ i++
123
+ }
124
+
125
+ let consumed = compound.tag !== '*' || body[start] === '*'
126
+ for (;;) {
127
+ const ch = body[i]
128
+ if (ch === '.') {
129
+ const m = new RegExp(`^\\.(${IDENT}+)`).exec(body.slice(i))
130
+ if (!m) throw new SelectorError(`类名不合法(位置 ${i}): "${body}"`)
131
+ compound.classes.push(m[1])
132
+ i += m[0].length
133
+ consumed = true
134
+ continue
135
+ }
136
+ if (ch === '#') {
137
+ const m = new RegExp(`^#(${IDENT}+)`).exec(body.slice(i))
138
+ if (!m) throw new SelectorError(`ID 不合法(位置 ${i}): "${body}"`)
139
+ if (compound.id) throw new SelectorError(`重复 ID 选择器: "${body}"`)
140
+ compound.id = m[1]
141
+ i += m[0].length
142
+ consumed = true
143
+ continue
144
+ }
145
+ if (ch === '[') {
146
+ const { attr, next } = readAttrSelector(body, i)
147
+ compound.attrs.push(attr)
148
+ i = next
149
+ consumed = true
150
+ continue
151
+ }
152
+ if (ch === ':') {
153
+ if (body[i + 1] === ':') throw new SelectorError(`伪元素只能出现在选择器末尾: "${body}"`)
154
+ const m = /^:([-\w]+)(?:\(\s*(\d+)\s*\))?/.exec(body.slice(i))
155
+ if (!m) throw new SelectorError(`伪类不合法(位置 ${i}): "${body}"`)
156
+ const kind = m[1].toLowerCase()
157
+ if (kind === 'first-child') compound.pseudoClasses.push({ kind: 'first-child' })
158
+ else if (kind === 'last-child') compound.pseudoClasses.push({ kind: 'last-child' })
159
+ else if (kind === 'nth-child') {
160
+ if (!m[2]) throw new SelectorError(`:nth-child 需要数字参数,如 :nth-child(2):${body}`)
161
+ compound.pseudoClasses.push({ kind: 'nth-child', n: Number(m[2]) })
162
+ } else {
163
+ throw new SelectorError(`不支持的伪类 :${kind}(支持 :first-child / :last-child / :nth-child(k))`)
164
+ }
165
+ i += m[0].length
166
+ consumed = true
167
+ continue
168
+ }
169
+ break
170
+ }
171
+ if (!consumed) throw new SelectorError(`无法解析选择器(位置 ${i}): "${body}"`)
172
+ return { compound, next: i }
173
+ }
174
+
175
+ /** 读取 [attr] / [attr op value];op ∈ = ^= $= *= ~= |=。 */
176
+ function readAttrSelector(body, start) {
177
+ const close = body.indexOf(']', start)
178
+ if (close < 0) throw new SelectorError(`属性选择器缺少 ']': "${body.slice(start)}"`)
179
+ const inner = body.slice(start + 1, close).trim()
180
+ const m = /^(-?[_a-zA-Z][-\w]*)(?:\s*(=|\^=|\$=|\*=|~=|\|=)\s*(.+))?$/.exec(inner)
181
+ if (!m) throw new SelectorError(`属性选择器不合法: [${inner}]`)
182
+ const name = m[1].toLowerCase()
183
+ const op = m[2] || null
184
+ let value = null
185
+ if (op) {
186
+ value = m[3].trim()
187
+ if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2)
188
+ || (value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
189
+ value = value.slice(1, -1)
190
+ }
191
+ if (!value) throw new SelectorError(`属性选择器值不能为空: [${inner}]`)
192
+ }
193
+ return { attr: { name, op, value }, next: close + 1 }
194
+ }
195
+
196
+ /** 单个复合选择器是否匹配节点。 */
197
+ function matchCompound(node, compound) {
198
+ if (!isElement(node)) return false
199
+ if (compound.tag !== '*' && node.tag !== compound.tag) return false
200
+ if (compound.id && node.attrs.id !== compound.id) return false
201
+ for (const cls of compound.classes) {
202
+ const list = typeof node.attrs.class === 'string' ? node.attrs.class.split(/\s+/).filter(Boolean) : []
203
+ if (!list.includes(cls)) return false
204
+ }
205
+ for (const { name, op, value } of compound.attrs) {
206
+ const actual = node.attrs[name]
207
+ if (actual === undefined) return false
208
+ if (op === null) continue
209
+ switch (op) {
210
+ case '=': if (actual !== value) return false; break
211
+ case '^=': if (!actual.startsWith(value)) return false; break
212
+ case '$=': if (!actual.endsWith(value)) return false; break
213
+ case '*=': if (!actual.includes(value)) return false; break
214
+ case '~=': if (!actual.split(/\s+/).includes(value)) return false; break
215
+ case '|=': if (actual !== value && !actual.startsWith(`${value}-`)) return false; break
216
+ default: return false
217
+ }
218
+ }
219
+ for (const pseudo of compound.pseudoClasses) {
220
+ const info = siblingInfo(node)
221
+ if (pseudo.kind === 'first-child' && info.nth !== 1) return false
222
+ if (pseudo.kind === 'last-child' && info.nth !== info.total) return false
223
+ if (pseudo.kind === 'nth-child' && info.nth !== pseudo.n) return false
224
+ }
225
+ return true
226
+ }
227
+
228
+ /**
229
+ * 元素兄弟位置索引缓存(父节点 → Map<节点, {nth, total, prevRaw}>)。
230
+ * 结构伪类与相邻组合器在高Sibling数页面(如 5 万元素列表)上如果每次
231
+ * 都重建过滤数组会是 O(n²),这里每个父节点只计算一次,查询 O(1)。
232
+ * 文档树解析后不再修改,WeakMap 随节点生命周期回收,无失效问题。
233
+ */
234
+ const siblingIndexCache = new WeakMap()
235
+
236
+ function siblingInfo(node) {
237
+ const parent = node.parent
238
+ if (!parent) return { nth: 1, total: 1, prevRaw: -1 }
239
+ let cache = siblingIndexCache.get(parent)
240
+ if (!cache) {
241
+ cache = new Map()
242
+ let nth = 0
243
+ let prevRaw = -1
244
+ const children = parent.children || []
245
+ for (let i = 0; i < children.length; i++) {
246
+ const child = children[i]
247
+ if (!isElement(child)) continue
248
+ nth++
249
+ cache.set(child, { nth, total: 0, prevRaw, selfRaw: i })
250
+ prevRaw = i
251
+ }
252
+ for (const info of cache.values()) info.total = nth
253
+ siblingIndexCache.set(parent, cache)
254
+ }
255
+ return cache.get(node) || { nth: 1, total: 1, prevRaw: -1 }
256
+ }
257
+
258
+ /** 节点的前一个元素兄弟(相邻组合器用)。 */
259
+ function prevElementSibling(node) {
260
+ const info = siblingInfo(node)
261
+ if (info.prevRaw < 0 || !node.parent) return null
262
+ return (node.parent.children || [])[info.prevRaw] || null
263
+ }
264
+
265
+ /**
266
+ * 自右向左验证组合器链:node 已匹配 compounds[index],
267
+ * 向上验证 compounds[0..index-1]。#document 不参与匹配。
268
+ */
269
+ function verifyPrefix(node, selector, index) {
270
+ if (index === 0) return true
271
+ const { compounds, combinators } = selector
272
+ const comb = combinators[index - 1]
273
+ const target = compounds[index - 1]
274
+ if (comb === 'child') {
275
+ const parent = node.parent
276
+ if (!parent) return false
277
+ return matchCompound(parent, target) && verifyPrefix(parent, selector, index - 1)
278
+ }
279
+ if (comb === 'adjacent') {
280
+ const prev = prevElementSibling(node)
281
+ if (!prev) return false
282
+ return matchCompound(prev, target) && verifyPrefix(prev, selector, index - 1)
283
+ }
284
+ // descendant:任何祖先
285
+ let ancestor = node.parent
286
+ while (ancestor) {
287
+ if (matchCompound(ancestor, target) && verifyPrefix(ancestor, selector, index - 1)) return true
288
+ ancestor = ancestor.parent
289
+ }
290
+ return false
291
+ }
292
+
293
+ /** 一个分组是否整体匹配节点。 */
294
+ function matchesSelector(node, selector) {
295
+ const last = selector.compounds.length - 1
296
+ return matchCompound(node, selector.compounds[last])
297
+ && verifyPrefix(node, selector, last)
298
+ }
299
+
300
+ /**
301
+ * 在 root 子树内按文档序收集命中节点(不含 root 自身)。
302
+ * selectorList 为空时返回空;selectorOf 为空时每个节点只归属第一个命中的
303
+ * 分组(与浏览器 querySelectorAll 去重一致)。
304
+ */
305
+ function matchNodes(root, selectorList, { perSelector = false } = {}) {
306
+ const out = []
307
+ const seen = perSelector ? null : new Set()
308
+ const walk = (node) => {
309
+ for (const child of node.children || []) {
310
+ if (child.tag === '#text' || child.tag === '#comment') continue
311
+ for (const selector of selectorList) {
312
+ if (matchesSelector(child, selector)) {
313
+ if (perSelector) out.push([child, selector])
314
+ else if (!seen.has(child)) { seen.add(child); out.push([child, selector]) }
315
+ if (!perSelector) break
316
+ }
317
+ }
318
+ walk(child)
319
+ }
320
+ }
321
+ walk(root)
322
+ return out
323
+ }
324
+
325
+ /** 仅供测试/内部使用:返回命中的原始节点列表。 */
326
+ export function selectAll(root, selectorText) {
327
+ return matchNodes(root, parseSelectorList(selectorText)).map(([node]) => node)
328
+ }
329
+
330
+ /** 元素子树内的文本节点对象列表(#text 节点,非字符串),按文档序。 */
331
+ function textNodeList(node) {
332
+ const out = []
333
+ const walk = (current) => {
334
+ for (const child of current.children || []) {
335
+ if (child.tag === '#text') out.push(child)
336
+ else if (child.tag !== '#comment') walk(child)
337
+ }
338
+ }
339
+ walk(node)
340
+ return out
341
+ }
342
+
343
+ /** 收集元素(含自身子树)内的全部文本内容,按文档序。 */
344
+ export function textNodesOf(node) {
345
+ return textNodeList(node).map((n) => n.text)
346
+ }
347
+
348
+ /** 空白归一化:折叠连续空白为单空格并去首尾。 */
349
+ export function normalizeText(text) {
350
+ return String(text ?? '').replace(/\s+/g, ' ').trim()
351
+ }
352
+
353
+ /** 元素包装对象:对服务调用方暴露 Scrapy 风格 API(attrib/text/css)。 */
354
+ export function wrapElement(node, options = {}) {
355
+ return {
356
+ get tag() { return node.tag },
357
+ get attrib() { return { ...node.attrs } },
358
+ get text() {
359
+ const joined = textNodesOf(node).join('')
360
+ return options.whitespace === 'keep' ? joined : normalizeText(joined)
361
+ },
362
+ css(selector) { return extract(node, selector, options) },
363
+ /** 原始节点(测试/序列化用,不对外文档化)。 */
364
+ node,
365
+ }
366
+ }
367
+
368
+ /**
369
+ * 执行选择器提取。
370
+ *
371
+ * 逗号分组的语义与 parsel(XPath union)对齐:每组独立匹配,
372
+ * 结果按文档序合并、按位置去重;元素结果返回包装对象,
373
+ * ::text/::attr 返回字符串。
374
+ *
375
+ * @param {object} root 解析后的文档/元素节点
376
+ * @param {string} selectorText 选择器(可含 ::text / ::attr(name),支持逗号分组)
377
+ * @param {object} [options]
378
+ * @param {'normalize'|'keep'} [options.whitespace='normalize'] ::text 的空白处理
379
+ * @returns {Array<string|object>} 字符串(::text/::attr)或元素包装对象
380
+ */
381
+ export function extract(root, selectorText, options = {}) {
382
+ const { whitespace = 'normalize' } = options
383
+ const selectorList = parseSelectorList(selectorText)
384
+
385
+ /* DFS 序号:同一文本节点被多组命中时按位置去重(XPath union 语义) */
386
+ const ordinals = new Map()
387
+ let counter = 0
388
+ const numberNodes = (node) => {
389
+ for (const child of node.children || []) {
390
+ if (child.tag === '#comment') continue
391
+ ordinals.set(child, counter++)
392
+ if (child.tag !== '#text') numberNodes(child)
393
+ }
394
+ }
395
+ numberNodes(root)
396
+
397
+ /* 排序键:序号×3 + 类别(元素 0 / 属性 1 / 文本 2),属性挂在其元素之后、子节点之前 */
398
+ const keyOf = (node, kind) => ordinals.get(node) * 3 + kind
399
+ const items = []
400
+ for (const [node, selector] of matchNodes(root, selectorList, { perSelector: true })) {
401
+ if (!selector.pseudo) { items.push({ key: keyOf(node, 0), value: wrapElement(node, options) }); continue }
402
+ if (selector.pseudo.kind === 'text') {
403
+ for (const textNode of textNodeList(node)) {
404
+ const value = whitespace === 'keep' ? textNode.text : normalizeText(textNode.text)
405
+ if (whitespace === 'keep' || value) items.push({ key: keyOf(textNode, 2), value })
406
+ }
407
+ } else {
408
+ const value = node.attrs[selector.pseudo.name]
409
+ if (value !== undefined) items.push({ key: keyOf(node, 1), value })
410
+ }
411
+ }
412
+ items.sort((a, b) => a.key - b.key)
413
+ const out = []
414
+ const seenKeys = new Set()
415
+ for (const item of items) {
416
+ if (seenKeys.has(item.key)) continue
417
+ seenKeys.add(item.key)
418
+ out.push(item.value)
419
+ }
420
+ return out
421
+ }
422
+
423
+ /** parse(html) 顶层入口:返回带 css() 的文档包装。 */
424
+ export function createSelectorDocument(html, options = {}) {
425
+ const root = parseHtml(html)
426
+ return wrapElement(root, options)
427
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capyclaw/scrapling",
3
- "version": "1.0.2",
4
- "description": "Scrapling 网页抓取集成:支持 HTTP 请求、隐身浏览器、JavaScript 渲染、Cloudflare 绕过、并发爬虫和数据导出",
3
+ "version": "1.1.0",
4
+ "description": "Scrapling 网页抓取集成:HTTP 抓取 + 纯 Node CSS 选择器提取 + 可视化爬虫工作台(浏览器打开即用)",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
7
7
  "exports": {
@@ -26,15 +26,22 @@
26
26
  },
27
27
  "meta": {
28
28
  "title": "Scrapling 网页抓取",
29
- "description": "强大的网页抓取工具:支持快速 HTTP 请求、隐身浏览器模式、JavaScript 渲染、Cloudflare 自动绕过、CSS/XPath 选择器、并发爬虫、代理轮换和多格式数据导出(JSON/CSV/XML)。"
29
+ "description": "网页数据爬取工具:HTTP 抓取、CSS 选择器提取(::text/::attr,纯 Node 实现)、可视化爬虫工作台(http://127.0.0.1:39640/,步骤回放 + 选择器试玩 + JSON/CSV 导出,内置离线演示页)。浏览器渲染与 XPath 依赖外部 Python scrapling,未实现并如实标注。"
30
30
  },
31
31
  "files": [
32
32
  "lib/",
33
33
  "client/",
34
+ "server/",
35
+ "ui/",
36
+ "demo/",
34
37
  "cordis.patch.yml",
35
38
  "README.md"
36
39
  ],
37
- "scripts": {},
40
+ "scripts": {
41
+ "start": "node server/server.mjs",
42
+ "test": "node --test \"test/*.test.mjs\"",
43
+ "test:internet": "node test/internet-campaign.mjs"
44
+ },
38
45
  "engines": {
39
46
  "node": ">=18",
40
47
  "dsh": "^0.2.0-rc.2"