@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
package/lib/host.mjs
CHANGED
|
@@ -1,25 +1,44 @@
|
|
|
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
|
+
* - 由 dsh-service-broker 作为独立进程管理;Cordis 进程不监听业务端口;
|
|
14
|
+
* - 依赖注入可选:workbench: false 可只注册进程内 fetch/parse API;
|
|
15
|
+
* - 通过 webserver/index-inject 注入 broker 返回的 URL,浏览器半挂面板。
|
|
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
|
|
34
|
+
export const inject = ['serviceBroker']
|
|
35
|
+
|
|
36
|
+
const SERVICE_ID = 'scrapling-workbench'
|
|
18
37
|
|
|
19
38
|
function notImplemented(feature) {
|
|
20
39
|
const error = new Error(
|
|
21
|
-
`[dsh-scrapling] ${feature}
|
|
22
|
-
'请使用 fetch()
|
|
40
|
+
`[dsh-scrapling] ${feature} 未实现:浏览器渲染与 XPath 依赖外部 Python scrapling 运行时。` +
|
|
41
|
+
'请使用 fetch()/parse()(HTTP 抓取 + CSS 选择器),或另行部署 scrapling 服务后通过 HTTP 调用。',
|
|
23
42
|
)
|
|
24
43
|
error.code = 'NOT_IMPLEMENTED'
|
|
25
44
|
return error
|
|
@@ -28,56 +47,112 @@ function notImplemented(feature) {
|
|
|
28
47
|
export async function apply(ctx, config = {}) {
|
|
29
48
|
const { value: cfg, issues } = resolveConfig(config, {
|
|
30
49
|
envPrefix: 'DSH_SCRAPLING',
|
|
31
|
-
defaults: {
|
|
50
|
+
defaults: {
|
|
51
|
+
enabled: true,
|
|
52
|
+
port: 'auto',
|
|
53
|
+
host: '127.0.0.1',
|
|
54
|
+
timeoutMs: 20000,
|
|
55
|
+
workbench: true,
|
|
56
|
+
},
|
|
32
57
|
fields: {
|
|
33
58
|
enabled: { env: 'ENABLED', type: 'boolean' },
|
|
59
|
+
port: { env: 'PORT', type: 'string' },
|
|
60
|
+
host: { env: 'HOST' },
|
|
34
61
|
timeoutMs: { env: 'TIMEOUT_MS', type: 'number' },
|
|
35
62
|
userAgent: { env: 'USER_AGENT' },
|
|
63
|
+
workbench: { env: 'WORKBENCH', type: 'boolean' },
|
|
36
64
|
},
|
|
37
65
|
})
|
|
38
|
-
|
|
39
|
-
|
|
66
|
+
for (const issue of issues) ctx.logger?.warn?.(`[dsh-scrapling] 配置: ${issue}`)
|
|
67
|
+
const port = cfg.port === 'auto' ? 'auto' : Number(cfg.port)
|
|
68
|
+
if (port !== 'auto' && (!Number.isInteger(port) || port < 1 || port > 65535)) {
|
|
69
|
+
ctx.logger?.warn?.(`[dsh-scrapling] 非法 port=${cfg.port},回退为 broker 自动分配`)
|
|
40
70
|
}
|
|
71
|
+
const servicePort = port === 'auto' || !Number.isInteger(port) || port < 1 || port > 65535 ? 'auto' : port
|
|
41
72
|
|
|
42
73
|
if (!cfg.enabled) {
|
|
43
74
|
ctx.logger?.info?.('[dsh-scrapling] 已按配置禁用,不注册 scrapling 服务')
|
|
44
75
|
return
|
|
45
76
|
}
|
|
46
77
|
|
|
78
|
+
const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
79
|
+
const crawler = createCrawler({ timeoutMs: cfg.timeoutMs, userAgent: cfg.userAgent })
|
|
80
|
+
|
|
47
81
|
ctx.provide('scrapling', {
|
|
48
82
|
/** 普通 HTTP 抓取(真实实现)。 */
|
|
49
83
|
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,
|
|
84
|
+
const record = await crawler.crawl({ url, timeoutMs: options.timeoutMs, userAgent: options.userAgent || options.headers?.['user-agent'] })
|
|
85
|
+
if (record.error) {
|
|
86
|
+
const error = new Error(record.error.message)
|
|
87
|
+
error.code = record.error.code
|
|
88
|
+
error.hint = record.error.hint
|
|
89
|
+
throw error
|
|
66
90
|
}
|
|
91
|
+
return { url: record.url, status: record.status, ok: record.ok, headers: {}, html: record.html }
|
|
67
92
|
},
|
|
68
93
|
|
|
69
|
-
/**
|
|
94
|
+
/** 浏览器渲染:未实现(诚实声明,不伪造结果)。 */
|
|
70
95
|
async fetchWithBrowser() {
|
|
71
96
|
throw notImplemented('fetchWithBrowser')
|
|
72
97
|
},
|
|
73
98
|
|
|
74
|
-
/**
|
|
75
|
-
parse() {
|
|
76
|
-
|
|
99
|
+
/** HTML → 文档包装:css('.a .b::text') / css('a::attr(href)')。 */
|
|
100
|
+
parse(html, options = {}) {
|
|
101
|
+
return createSelectorDocument(html, options)
|
|
77
102
|
},
|
|
103
|
+
|
|
104
|
+
/** 工作台爬取流水线(带步骤计时,工作台界面数据源)。 */
|
|
105
|
+
crawler,
|
|
78
106
|
})
|
|
79
107
|
|
|
108
|
+
/* 工作台由 broker 独立拉起;Cordis 进程只注册 API 与 sidebar URL。 */
|
|
109
|
+
let serviceBroker = null
|
|
110
|
+
let stopServiceOnDispose = false
|
|
111
|
+
let serviceUrl = ''
|
|
112
|
+
if (cfg.workbench) {
|
|
113
|
+
const broker = ctx.serviceBroker
|
|
114
|
+
serviceBroker = broker || null
|
|
115
|
+
if (!broker || typeof broker.start !== 'function') {
|
|
116
|
+
ctx.logger?.warn?.('[dsh-scrapling] 缺少 ctx.serviceBroker,工作台未启动;fetch/parse API 仍可用')
|
|
117
|
+
} else {
|
|
118
|
+
const serviceFile = path.join(packageDir, 'server', 'server.mjs')
|
|
119
|
+
const spec = {
|
|
120
|
+
id: SERVICE_ID,
|
|
121
|
+
cmd: [process.execPath, serviceFile, '--port', '${PORT}', '--host', cfg.host],
|
|
122
|
+
env: {
|
|
123
|
+
DSH_SCRAPLING_TIMEOUT_MS: String(cfg.timeoutMs),
|
|
124
|
+
...(cfg.userAgent ? { DSH_SCRAPLING_USER_AGENT: String(cfg.userAgent) } : {}),
|
|
125
|
+
},
|
|
126
|
+
ports: { main: servicePort },
|
|
127
|
+
url: 'http://127.0.0.1:${PORT}',
|
|
128
|
+
healthPath: '/healthz',
|
|
129
|
+
keepAlive: true,
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const started = await broker.start(spec)
|
|
133
|
+
if (!started?.url) throw new Error('serviceBroker.start 未返回服务 url')
|
|
134
|
+
serviceUrl = started.url.replace(/\/$/, '')
|
|
135
|
+
stopServiceOnDispose = true
|
|
136
|
+
ctx.logger?.info?.(`[dsh-scrapling] broker 工作台已就绪: ${serviceUrl}/`)
|
|
137
|
+
ctx.on?.('webserver/index-inject', (table) => {
|
|
138
|
+
table.push({ kind: 'global', name: '__DSH_SCRAPLING__', value: { url: `${serviceUrl}/`, version: '1.1.1' } })
|
|
139
|
+
})
|
|
140
|
+
} catch (error) {
|
|
141
|
+
ctx.logger?.warn?.(`[dsh-scrapling] broker 工作台启动失败(fetch/parse API 仍可用): ${error.message}`)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
ctx.logger?.info?.('[dsh-scrapling] workbench=false,仅注册 scrapling API,不投递服务')
|
|
146
|
+
}
|
|
147
|
+
|
|
80
148
|
ctx.logger?.info?.(
|
|
81
|
-
`[dsh-scrapling] 已注册 scrapling
|
|
149
|
+
`[dsh-scrapling] 已注册 scrapling 服务(fetch + parse;浏览器/XPath 未实现,timeout=${cfg.timeoutMs}ms)`,
|
|
82
150
|
)
|
|
151
|
+
|
|
152
|
+
return async () => {
|
|
153
|
+
if (stopServiceOnDispose && serviceBroker && typeof serviceBroker.stop === 'function') {
|
|
154
|
+
const result = await serviceBroker.stop(SERVICE_ID)
|
|
155
|
+
if (result?.stopped) ctx.logger?.info?.('[dsh-scrapling] broker 已停止工作台服务')
|
|
156
|
+
}
|
|
157
|
+
}
|
|
83
158
|
}
|
|
@@ -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'
|