普贤教程 › 包参考
html 包
简化 HTML5 容错解析器(提取正文/简单选择器)
| 项 | 值 |
|---|---|
| 包名 | html |
| 版本 | 0.1.0 |
| 入口 | html.px |
| 分类 | 数据格式与编解码 |
| 文件数 / 行数 | 1 / 446 |
安装与引入
bash
pxpkg init # 首次 pxpkg add html@0.1.0 pxpkg install
px
import html所属分类教程:数据格式与编解码
公开接口
| 函数 | 参数 |
|---|---|
html_parse | text |
html_text | node |
html_query | root, selector |
其余 23 个 def(内部与辅助,可直接调用但不属稳定接口)
| 函数 | 参数 |
|---|---|
hx_void_tags | |
hx_raw_tags | |
hx_implicit_close | |
hx_new_node | tag |
hx_add_text | stack, s |
hx_open | stack, node |
hx_close_upto | stack, tag |
hx_find | text, start, ch |
hx_find_ci | text, start, needle |
hx_entities | |
hx_decode | s |
hx_is_name_start | c |
hx_is_name_char | c |
hx_is_space | c |
hx_parse_open | body |
hx_parse_end | body |
html_children | node |
html_attr | node, name |
html_tag | node |
hx_parse_selector | sel |
hx_match | node, tag, cls, id |
hx_collect | node, tag, cls, id, out |
html_escape | s |
包内说明(源码头注释)
text
============================================================ 普贤标准库:std.html —— 简化 HTML5 容错解析器(提取正文/简单选择器) ------------------------------------------------------------ 纯函数库(无 IO、无状态),编译/解释双模式一致。 面向「爬取正文 / 页面片段提取」场景的容错 HTML 子集解析器: 不校验标签闭合合法性——坏标签自动纠正(自动闭合/隐式闭合/忽略孤立结束标签)。 注释/doctype/script/style 内容按 HTML5 规则处理(raw text 不进正文)。 命名实体最小解码集:& < > " ' (数字实体保留原样)。 DOM 节点统一 dict:{tag, attrs, text, children} tag = 元素名(小写)| "#root" | "#text" | "#comment"(注释/doctype 丢弃不建节点) attrs = 属性 dict(名小写,无值属性记 "") text = 仅 #text 节点持有;children = 子节点 list html_parse(text) → #root 节点(永不失败:无法解析的片段按文本保留) html_text(node) → 剥标签取可见正文(跳过 script/style 内容,注释节点跳过) html_query(root, selector) → [node](tag[.class][#id] 简单选择,无空格后代组合) 用法: import std.html var dom = html_parse("<div class='a'><p>hi</p></div>") print(html_text(dom)) # hi var ns = html_query(dom, "p.a") # [<p 节点>] ============================================================ ---- void 元素(HTML5:不自闭合也不需闭合标签)----