在浏览器环境中,如果不想依赖 DOMParser
,同时需要从 HTML 字符串中提取所有 href
、action
、src
等标签属性,以下是几个轻量且高效的库推荐:
1. cheerio(纯浏览器版)
虽然 cheerio
常用于 Node.js,但可以通过 Browserify 或直接引入预构建的浏览器版本(如 cheerio.min.js
)在浏览器中使用。
特点:
- 类 jQuery API,操作简单。
- 不依赖 DOM,直接解析 HTML 字符串。
// 示例:浏览器中使用 cheerio
const cheerio = require('cheerio'); // 通过打包工具引入
// 或直接加载预构建的 <script src="cheerio.min.js"></script>
const html = '<a href="/link">Click</a><img src="image.png">';
const $ = cheerio.load(html);
const links = $('a[href], img[src], form[action]')
.map((i, el) => ({
href: $(el).attr('href'),
src: $(el).attr('src'),
action: $(el).attr('action')
}))
.get();
console.log(links); // [{href: "/link"}, {src: "image.png"}]
2. linkedom
一个轻量的 DOM 实现库,可以在浏览器中替代原生 DOMParser
。
特点:
- 无 DOM 依赖,解析速度快。
- 支持标准 DOM API(如
querySelectorAll
)。
import { parseHTML } from 'linkedom';
const html = '<form action="/submit"><img src="test.png"></form>';
const { document } = parseHTML(html);
const elements = document.querySelectorAll('[href],[src],[action]');
const results = Array.from(elements).map(el => ({
href: el.getAttribute('href'),
src: el.getAttribute('src'),
action: el.getAttribute('action')
}));
console.log(results); // [{action: "/submit"}, {src: "test.png"}]
3. htmlparser2
纯 JavaScript 实现的 HTML/XML 解析器,适用于流式处理。
特点:
- 极轻量级(~40KB),事件驱动式解析。
- 支持自定义属性提取逻辑。
import { parseDOM } from 'htmlparser2';
const html = '<a href="#top">Jump</a>';
const dom = parseDOM(html);
const attributes = [];
dom.forEach(node => {
if (node.type === 'tag' && node.attribs) {
const { href, src, action } = node.attribs;
if (href || src || action) attributes.push({ href, src, action });
}
});
console.log(attributes); // [{href: "#top"}]
4. fast-html-parser
针对性能优化的 HTML 解析器,有浏览器兼容版本。
import { parse } from 'fast-html-parser';
const html = '<img src="logo.png">';
const root = parse(html);
root.querySelectorAll('[src],[href],[action]').forEach(node => {
console.log(node.attributes); // {src: "logo.png"}
});
选择建议
库名 | 大小 | API风格 | 适用场景 |
---|---|---|---|
cheerio |
~200KB | jQuery-like | 复杂HTML操作(需打包) |
linkedom |
~50KB | Standard DOM | 需要DOM API但无原生依赖 |
htmlparser2 |
~40KB | Event-driven | 高性能流式解析 |
fast-html-parser |
~30KB | Simplified | 快速简单查询 |
若追求最小体积和灵活性,推荐 htmlparser2
;若习惯 jQuery API,选 cheerio
。
内容由零声教学AI助手提供,问题来源于学员提问