@dooboostore/dom-parser

中文文档
1.0.29发布于 2026/11/07MITTypeScriptESM + CJS近 30 天下载 3899

一个轻量级的DOM解析器,用于服务器侧 HTML 解析和操作,并配有完整的 DOM API 支持

中文使用文档
文档目录36 节
  1. 特征
  2. 浏览器等同
  3. 安装
  4. 快速启动
  5. 基本 HTML 分析
  6. 使用 parseHTML 工具快速设置
  7. 模板处理
  8. API 参考
  9. DOMPARSER 类
  10. 剖析HTML 工具函数
  11. 支持的 DOM API
  12. 使用大小写
  13. QQ HTML 处理和操纵
  14. * 服务器系统渲染(SSR)
  15. 电子邮件模板处理
  16. & 数据提取器
  17. 自定义元素注册
  18. 高级 DOM 有树华克的拖曳
  19. DOM 碎片创建和批量操作
  20. XQHTML 验证和清理
  21. 高级特性
  22. 文档重新装入
  23. 内存管理
  24. 基础 URL 配置
  25. CSS 选择复杂度
  26. 性能特征
  27. DOM 节点类参考
  28. 核心类
  29. DOM 节点类
  30. 高级接口
  31. 与替代品的比较
  32. 诉JSDOM案
  33. 欢呼声
  34. 五. 链接DOM
  35. 学习更多
  36. 许可证

@ dooboostore/dom-parser (英语)

NPM version Build and Test License: MIT

一个轻量级的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.textContent
  • element.setAttribute() 编号 : element.getAttribute()
    • element.appendChild() 编号 : element.removeChild()
    • form.elements (类别形式-所有者协会)/ control.form
    • select.size 编号 : select.multiple, (中文(简体) ), option.value 编号 : option.text
    • element.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 许可证。 。 。 .

版本与发布记录

@dooboostore/dom-parser 共发布 30 个版本,首次发布于 2025/10/09;过去 12 个月发布了 28 个版本。

版本发布日期距今
1.0.29latest2026/11/076 天前
1.0.282026/11/076 天前
1.0.272026/11/076 天前
1.0.262026/11/076 天前
1.0.252026/11/0112 天前
1.0.242026/11/0112 天前

关于 @dooboostore/dom-parser 的常见问题

@dooboostore/dom-parser 是什么?

一个轻量级的DOM解析器,用于服务器侧 HTML 解析和操作,并配有完整的 DOM API 支持

如何安装 @dooboostore/dom-parser?

在项目目录运行 npm install @dooboostore/dom-parser,或使用 pnpm add / yarn add / bun add。

@dooboostore/dom-parser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dooboostore/dom-parser 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@dooboostore/dom-parser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dooboostore/dom-parser 可以商用吗?

@dooboostore/dom-parser 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dooboostore/dom-parser 的下载量有多少?

根据 npm 官方下载统计,@dooboostore/dom-parser 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,899 次,日均约 130 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dooboostore/dom-parser 还在维护吗?

最新版本 1.0.29 发布于 2026/11/07(6 天前);至今共发布 30 个版本,其中过去 12 个月发布了 28 个;首次发布于 2025/10/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。