@ dooboostore/dom-parser (英语)
一个轻量级的DOM解析器,用于服务器侧 HTML 解析和操作,并配有完整的 DOM API 支持. 下面的每一个行为都与真正的Chromium——292个测试,都是绿色的,没有jsdom.
特征
- QQ 服务器Side DOM: 没有第三方依赖关系的Node.js环境完成 DOM 执行
- CSS 选择器支持齐全
querySelector财务报告和审定财务报表querySelectorAll有复杂选择器支持 - QQ 多格式:作为无害环境管理、CJS和UMD捆绑,以达到最大兼容性
- QQ 类型脚本: JSDoc 文档中包含的完整类型脚本定义
- 最小依赖性: 只取决于
@dooboostore/core; 轻而快, 适合无服务器环境 - QQ HTML 模板: 处理复杂的 HTML 模板、属性和自定义元素
- DOM 拖转器: 内建支持
TreeWalker财务报告和审定财务报表NodeIterator高效树道导航 - 自定义元素齐全
customElements.define()API 用于在服务器上注册和使用 Web 组件 - 标准规范: 执行标准 DOM API( 克里- 选择器、 附加设备、 内置HTML等)
- QQ 浏览器对等: 选择器匹配、IDL反射和序列化 浏览器等同 (见下文)
- * * 宣布阴影DOM数字 :
getHTML()编号 :setHTMLUnsafe()带有宣示性SSR管线的阴影根序列化 - QQ 内存效率: 适当收集垃圾
destroy()长期进程的方法
浏览器等同
行为被固定在真实的Chromium(通过Playwright)上,而不是对其他模仿者. 下面每个项目都是通过测试,而不是愿望:
- 选择器: 双人轴(
+, (中文(简体) ),~, (中文(简体) ),:has()具有锚固态, 明确:scope约束查询范围,绝对:is()编号 ::where()编号 ::not()内装:has(), (中文(简体) ),:nth-child(an+b of S), (中文(简体) ),of- 过滤计数、属性操作员(=, (中文(简体) ),~=, (中文(简体) ),|=, (中文(简体) ),^=, (中文(简体) ),$=, (中文(简体) ),*=, (中文(简体) ),i包括空值规则([a~=""], (中文(简体) ),[a^=""], (中文(简体) ),[a$=""], (中文(简体) ),[a*=""]永远不匹配;[a|=""]保留虚线列表语义) - IDL 反射数字 :
select.size编号 :select.multiple, (中文(简体) ),option.value编号 :option.text(脚本小树除外),form.elements与spec形式所有者协会(form=属性,没有祖先对错配的后退,control.form - 零处理数字 :
innerHTML编号 :innerText编号 :textContent设置清除null和 String()- coerce 其他一切, 完全像浏览器 - 序列化: SVG/MathML 案件保存(
<path>没有<PATH>),属性逃出(&, (中文(简体) ),<, (中文(简体) ),>,非破碎空间),声明式阴影 DOM回转
安装
# pnpm
pnpm add @dooboostore/dom-parser
# npm
npm install @dooboostore/dom-parser
# yarn
yarn add @dooboostore/dom-parser
快速启动
基本 HTML 分析
import { DomParser } from '@dooboostore/dom-parser';
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div id="app">
<h1>Hello World</h1>
<p class="content">This is a test paragraph.</p>
</div>
</body>
</html>
`;
const parser = new DomParser(html);
const document = parser.document;
// Use standard DOM APIs
const title = document.querySelector('title');
console.log(title?.textContent); // "Test Page"
const app = document.getElementById('app');
console.log(app?.innerHTML); // Contains the div content
使用 parseHTML 工具快速设置
import { parseHTML } from '@dooboostore/dom-parser';
// Quick way to get window object for SSR
const window = parseHTML(html);
const document = window.document;
// Perfect for setting up global DOM
global.window = window;
global.document = document;
模板处理
import { DomParser } from '@dooboostore/dom-parser';
// Parse HTML templates with complex attributes
const templateHtml = `
<div class="container">
<button onclick="handleClick(data)" disabled="false">
Click Me
</button>
<input value="user.name" placeholder="Enter name" />
</div>
`;
const parser = new DomParser(templateHtml);
const document = parser.document;
// Access and modify elements
const button = document.querySelector('button');
console.log(button?.getAttribute('onclick')); // "handleClick(data)"
const input = document.querySelector('input');
input?.setAttribute('value', 'new value');
API 参考
DOMPARSER 类
构造器
new DomParser(html: string, options?: DomParserOptions)
以提供的 HTML 字符串创建一个新的 DOM 解析实例.
参数:
html: 要解析的 HTML 字符串options: 可选配置对象
DOMPARSER 选项 :
interface DomParserOptions {
href?: string; // Base URL for the document
onUrlChange?: (url: string) => void; // Called whenever the parsed document's `location.href` changes (e.g. from code running against the parsed DOM setting `location.href` or using history APIs)
fetch?: typeof globalThis.fetch; // Custom fetch implementation used by `window.fetch()` inside the parsed environment
}
属性
document: 以完整的 DOM API 支持返回已解析的文档对象window: 返回服务器侧渲染兼容性窗口对象
剖析HTML 工具函数
函数签名
parseHTML(html: string, options?: DomParserOptions): Window
一个方便的功能,可以创建 DomParser 实例并直接返回窗口对象.
用法 :
import { parseHTML } from '@dooboostore/dom-parser';
// Quick setup for SSR
const window = parseHTML('<html><body><h1>Hello</h1></body></html>');
const document = window.document;
// Set up globals
global.window = window;
global.document = document;
// Use DOM APIs immediately
const h1 = document.querySelector('h1');
console.log(h1?.textContent); // "Hello"
支持的 DOM API
document.querySelector()编号 :document.querySelectorAll()document.getElementById()编号 :document.getElementsByClassName()element.innerHTML编号 :element.textContentelement.setAttribute()编号 :element.getAttribute()element.appendChild()编号 :element.removeChild()form.elements(类别形式-所有者协会)/control.formselect.size编号 :select.multiple, (中文(简体) ),option.value编号 :option.textelement.getHTML()编号 :element.setHTMLUnsafe()(宣布阴影DOM)
document.createElement()编号 :document.createTextNode()document.createDocumentFragment()NodeIterator编号 :TreeWalker- CSS 选择器解析复杂的表达式
- 事件处理和DOM操纵
- 自定义元素注册方式
customElements.define()(包括通过is=""和已分解元素的自动升级) - 基础SVG(
<svg>, (中文(简体) ),<circle>, (中文(简体) ),<rect>)和 MathML 元素识别与 70+ 标准 HTML 元素标记
使用大小写
QQ HTML 处理和操纵
import { DomParser } from '@dooboostore/dom-parser';
function processHtml(html: string) {
const parser = new DomParser(html);
const document = parser.document;
// Modify the DOM
const title = document.querySelector('title');
if (title) {
title.textContent = 'Processed Title';
}
// Add meta tags
const head = document.querySelector('head');
const meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', 'Processed content');
head?.appendChild(meta);
return document.documentElement.outerHTML;
}
* 服务器系统渲染(SSR)
import { parseHTML } from '@dooboostore/dom-parser';
// Quick setup with parseHTML utility
const templateHtml = fs.readFileSync('template.html', 'utf8');
const window = parseHTML(templateHtml);
// Set up global DOM for SSR
global.document = window.document;
global.window = window;
// Now your components can use DOM APIs on the server
电子邮件模板处理
import { DomParser } from '@dooboostore/dom-parser';
function generateEmailHtml(userData: {name: string, orderId: string}) {
const templateHtml = `
<html>
<body>
<h1>Hello <span class="user-name"></span>!</h1>
<p>Your order <strong class="order-id"></strong> has been confirmed.</p>
</body>
</html>
`;
const parser = new DomParser(templateHtml);
const document = parser.document;
// Inject data into the template
document.querySelector('.user-name')!.textContent = userData.name;
document.querySelector('.order-id')!.textContent = userData.orderId;
return document.documentElement.outerHTML;
}
& 数据提取器
import { DomParser } from '@dooboostore/dom-parser';
import { parseHTML } from '@dooboostore/dom-parser';
async function scrapeArticles(html: string) {
const window = parseHTML(html);
const document = window.document;
const articles = [];
const articleElements = document.querySelectorAll('article.post');
articleElements.forEach(el => {
const title = el.querySelector('h2')?.textContent || '';
const author = el.querySelector('.author')?.textContent || '';
const date = el.querySelector('.date')?.getAttribute('data-date') || '';
articles.push({ title, author, date });
});
return articles;
}
自定义元素注册
import { parseHTML } from '@dooboostore/dom-parser';
const window = parseHTML('<html><body></body></html>');
// Define a custom element (extend the parsed window's HTMLElement)
class MyCustomElement extends (window as any).HTMLElement {
connectedCallback() {
this.innerHTML = '<p>Custom Element Works!</p>';
}
}
// Register custom element
window.customElements.define('my-element', MyCustomElement);
// Create and use custom element
const doc = window.document;
const customEl = doc.createElement('my-element');
doc.body?.appendChild(customEl);
console.log(doc.body?.outerHTML);
// <body><my-element><p>Custom Element Works!</p></my-element></body>
高级 DOM 有树华克的拖曳
import { parseHTML } from '@dooboostore/dom-parser';
const html = `
<div class="container">
<h1>Title</h1>
<section>
<article>Item 1</article>
<article>Item 2</article>
</section>
</div>
`;
const window = parseHTML(html);
const document = window.document;
// Use TreeWalker for efficient traversal
const root = document.querySelector('.container');
const walker = document.createTreeWalker(
root,
window.NodeFilter.SHOW_ELEMENT,
null
);
let node = walker.nextNode();
while (node) {
console.log((node as Element).tagName, (node as Element).textContent);
node = walker.nextNode();
}
DOM 碎片创建和批量操作
import { parseHTML } from '@dooboostore/dom-parser';
const window = parseHTML('<html><body></body></html>');
const document = window.document;
// Create a document fragment for efficient batch operations
const fragment = document.createDocumentFragment();
for (let i = 1; i <= 5; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
const ul = document.createElement('ul');
ul.appendChild(fragment);
document.body?.appendChild(ul);
console.log(document.body?.outerHTML);
// Creates <ul> with 5 <li> items (fragment prevents multiple reflows)
XQHTML 验证和清理
import { DomParser } from '@dooboostore/dom-parser';
function sanitizeHtml(html: string): string {
const parser = new DomParser(html);
const document = parser.document;
// Remove all scripts
document.querySelectorAll('script').forEach(el => {
el.parentNode?.removeChild(el);
});
// Remove event attributes
const allElements = document.querySelectorAll('*');
allElements.forEach(el => {
Array.from(el.attributes || []).forEach(attr => {
if (attr.name.startsWith('on')) {
el.removeAttribute(attr.name);
}
});
});
return document.documentElement.outerHTML;
}
高级特性
文档重新装入
用新 HTML 内容更新已解析的文档而不创建新解析器 :
import { DomParser } from '@dooboostore/dom-parser';
const parser = new DomParser('<html><body><h1>Original</h1></body></html>');
// Later, load new HTML
parser.loadHTML('<html><body><h2>Updated</h2></body></html>');
const title = parser.document.querySelector('h2');
console.log(title?.textContent); // "Updated"
内存管理
正确清理长期应用程序的解析例 :
import { DomParser } from '@dooboostore/dom-parser';
const parser = new DomParser(largeHtml);
// Process document
const results = processDocument(parser.document);
// Destroy when done to free memory
parser.destroy();
基础 URL 配置
设置相对 URL 分辨率和 API 调用的基础 URL :
import { DomParser } from '@dooboostore/dom-parser';
const parser = new DomParser(html, {
href: 'https://example.com/page/'
});
console.log(parser.window.location.href); // "https://example.com/page/"
CSS 选择复杂度
支持复杂的 CSS 选择器查询 :
import { parseHTML } from '@dooboostore/dom-parser';
const html = `
<div class="container">
<article class="featured">
<h2>Title</h2>
<p class="summary">Summary text</p>
</article>
<article>
<h2>Another</h2>
</article>
</div>
`;
const window = parseHTML(html);
const doc = window.document;
// Complex selectors
const featured = doc.querySelector('article.featured > p.summary');
const allHeadings = doc.querySelectorAll('article > h2');
const byAttribute = doc.querySelectorAll('[class~="featured"]');
console.log(featured?.textContent); // "Summary text"
console.log(allHeadings.length); // 2
性能特征
按参考运行(节点24,Apple硅,500-element文档,中值为21跑)测量:
- 解析:~3.7 ms-同架:连通-5.0 ms,jsdom~20 ms
- 序列化 (单位:千美元)
outerHTML: ~1.1毫秒(秒) - 查询选择器: ~0.3 ms 缓存; 冷独选者支付编译成本一次, 然后缓存
- 无第三方依赖:没有jsdom, chaiio,或其他重量级的剖析器——只有
@dooboostore/core - 轻巧: 适合微服务和无服务器环境
- 内存效率:把对适当收集垃圾的关切明确分开
- 树形Walker 节点编辑器( N): 高效的 DOM 旋转而未将整棵树装入内存
DOM 节点类参考
核心类
多姆帕塞尔
主类用于解析 HTML 字符串并创建 DOM 环境.
// Constructor
new DomParser(html: string, options?: DomParserOptions)
// Methods
get document(): Document // Access the parsed document
get window(): Window // Access the window object
loadHTML(html: string): void // Clear head/body and parse new HTML into the same document
parseHTML(html: string): void // Parse HTML into the current document (used by the constructor)
destroy(): void // Destroy parser and free memory
// Options
interface DomParserOptions {
href?: string; // Base URL for the document
onUrlChange?: (url: string) => void; // Fires when the parsed document's location.href changes
fetch?: typeof globalThis.fetch; // Custom fetch implementation for window.fetch()
}
剖析HTML 工具
SSR 设置的快用功能 :
const window = parseHTML(html, options?: DomParserOptions);
// Returns Window object directly
// window.document available immediately
DOM 节点类
该包提供标准DOM接口的TypeScript执行. 从根导出 :
- 窗口库编号:
window执行(地点、历史、导航、,customElements, (中文(简体) ),fetch, DOM 构造器) - 文档Base: 完全执行文件
querySelector, (中文(简体) ),getElementById, (中文(简体) ),createElement等 (中文(简体) ). - 节点Base 编号 : 元素库 编号 : HTML 元素库: 节点、元素(属性管理)和 HTML 元素基类
- HTML 元素: 标准 HTML 元素类
- 文档断块Base: 分批操作的文档碎片
- 阴影鼠标Base: 阴影 DOM 支持
- 元素事实静态
createElement(tagName, ownerDocument?)加号getSupportedTagNames()(和 HTML/SVG/MathML 变体)
文本节点( E)TextBase)和评论(eComment)通过内部执行和创建 document.createTextNode() 编号 : createComment()。 。 。 .
高级接口
// Importable from '@dooboostore/dom-parser'
NodeIterator // Traverse DOM nodes sequentially (also returned by document.createNodeIterator())
NodeFilter // Node-filtering constants (SHOW_ELEMENT, SHOW_TEXT, ...)
ParentNodeBase // Base class implementing child-node management
ChildNodeBase // Base class implementing parent/sibling navigation
// Not a top-level export — obtained via document.createTreeWalker(), not imported directly
TreeWalker // Efficient DOM tree traversal with filters
与替代品的比较
诉JSDOM案
- dom- parser 文档: 轻量级, 零第三方依赖性, 单目的; 以 ~3. 7 ms 来解析参考500 元素文档
- 日记: 完整浏览器模拟, 更大的捆绑, 更多的间接费用( 相同文档上为~ 20 ms)
欢呼声
- dom- parser 文档:纯 DOM API 相容性(
querySelector, (中文(简体) ),form.elements, IDL 反射), TypeScript, 不需要 j 查询包 - 欢呼声: jQuery API 语法,为 jQuery 用户所熟悉
五. 链接DOM
- dom- parser 文档: 更简单的核心, 聚焦于 HTML 解析
- 链接 DOM: 更全面的图书馆一级生态系统
学习更多
详细的API文件,包括所有支持的DOM方法和使用实例,可在我们的文件网站上查阅.
许可证
此软件包根据 MIT 许可证。 。 。 .