如何在 Python 中使用 DOM
Aspose.HTML FOSS 用于 Python 模型的 HTML,作为基于标准的 DOM:Document 创建节点,Element 管理属性,Node 提供树操作。此指南构建一个小树并读取其结构,使用 pip 进行安装。
分步指南
步骤 1:安装软件包
安装软件包:
git clone https://github.com/aspose-html-foss/Aspose.HTML-FOSS-for-Python.git
cd Aspose.HTML-FOSS-for-Python
pip install -e .然后确认软件包元数据:
pip show aspose-html-foss步骤 2:导入所需的类
from aspose_html.dom import Document步骤 3:创建文档和元素
Document 是节点工厂;create_element() 返回一个新元素,你可以使用 append_child() 附加它:
doc = Document()
el = doc.create_element("div")
doc.append_child(el)步骤 4:设置属性
set_attribute() 写入标记属性;类和 id 驱动后续的 CSS 匹配:
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")步骤 5:读取结构
get_element_by_id() 检索元素,get_attribute() 返回其属性,has_child_nodes() 确认结构:
found = doc.get_element_by_id("bar")
print(found.get_attribute("class"))
print(doc.has_child_nodes())常见问题及解决方案
按 id 查找未返回任何内容。 元素的 id 属性必须在 get_element_by_id() 被调用时,且元素必须附加到文档树上。
属性读取返回意外的值。 get_attribute() 返回上一次使用 set_attribute(); 检查属性名称是否有拼写错误——它们是普通字符串。
从其他文档创建的节点行为异常。 节点是文档范围的。通过相同的方式创建它们 Document,或使用它们进行转移 import_node()/adopt_node().
常见问题
Document 可以创建哪些节点类型?
元素、文本节点、注释和文档片段 —— 通过 create_element()、create_text_node()、create_comment() 和 create_document_fragment()。
如何移动或删除已有节点?
使用 Node 操作:insert_before()、remove_child()、replace_child() 和 clone_node()。
我可以解析已有的标记,而不是手动构建树吗?
是的 — 对页面使用 HTMLDocument.parse(),对代码片段使用 HTMLDocument.parse_fragment() 会生成相同类型的树。