介绍
DOM 层是 Aspose.HTML FOSS 为 Python 的核心。它按照标准的方式对 HTML 页面进行建模——将其视为由 Document、Element、Text、Comment 和 DocumentFragment 节点组成的树——并提供操作,让你能够在没有浏览器参与的情况下,从 Python 代码构建、检查和重新排列该树。
本文逐步介绍主要的 DOM 功能:创建节点、管理属性、使用 Node 操作移动子树、解析片段,以及在树构建完成后再次查找元素。此处展示的所有内容都随 aspose-html-foss 包在 PyPI 上发布,采用 MIT 许可证,并在 3.10 或更高版本的纯 Python 环境中运行。
关键特性
创建文档和元素
Document 是节点工厂:用于元素的 create_element()、用于文本的 create_text_node()、用于注释的 create_comment(),以及用于轻量容器的 create_document_fragment()。新节点通过 append_child() 附加到树上:
from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
doc.append_child(el)
管理属性
属性在 Element.set_attribute()、get_attribute()、has_attribute() 和 remove_attribute() 之间来回传递。当你需要将属性作为对象而非字符串时,Attr 类对单个属性节点进行建模:
from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")
doc.append_child(el)
节点的树操作
每个节点都继承自 Node 的标准树工具集:用于结构更改和检查的 insert_before()、remove_child()、replace_child()、clone_node() 和 contains(),以及用于遍历的 child_nodes、parent_node、first_child,还有用于读取或分配子树文本的 text_content。get_root_node() 和 has_child_nodes() 直接回答常见的结构性问题。
解析片段和相邻标记
HTMLDocument.parse() 处理完整页面,HTMLDocument.parse_fragment() 处理部分标记。对于相对于现有元素的精确插入,Element 提供 insert_adjacent_html()、insert_adjacent_text() 和 insert_adjacent_element() —— 标准的四位置插入 API。Document.import_node() 和 adopt_node() 在文档之间移动节点。
查找并读取回
Document.get_element_by_id() 根据其 id 属性检索元素。结合来自 CSSOM 层的计算样式访问,你可以验证子树包含什么以及它将如何被样式化:
from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet
doc = Document()
el = doc.create_element("div")
el.set_attribute("id", "bar")
doc.append_child(el)
sheet = CSSStyleSheet()
sheet.replace_sync("#bar { color: blue }")
doc.attach_style_sheet(sheet)
style = el.get_computed_style()
print(style.get_property_value("color"))
快速入门
从 PyPI 安装:
asposefoss/html is not yet published — build from source until it ships. See the project README for build instructions.构建一个小树,使用属性标记它,并确认结构:
from aspose_html.dom import Document
doc = Document()
container = doc.create_element("div")
container.set_attribute("id", "content")
doc.append_child(container)
child = doc.create_element("p")
container.append_child(child)
print(container.has_child_nodes())
print(doc.get_element_by_id("content").get_attribute("id"))
开源与许可
Aspose.HTML FOSS 用于 Python 的许可证为 MIT — 可免费用于商业使用、修改和再分发。代码托管在 GitHub,发布版本则发布到 PyPI,形式为 aspose-html-foss。