はじめに

DOM レイヤーは Python 用の Aspose.HTML FOSS の中核です。標準が行うように、HTML ページを DocumentElementTextCommentDocumentFragment ノードのツリーとしてモデル化し、ブラウザを介さずに Python コードからそのツリーを構築、検査、再配置するための操作を提供します。

この記事では、主な DOM 機能—ノードの作成、属性の管理、Node 操作によるサブツリーの移動、フラグメントのパース、ツリー構築後の要素の再検索—について順に説明します。ここで示したすべては PyPI の aspose-html-foss パッケージに含まれ、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_nodesparent_nodefirst_child、サブツリーのテキストを読み取ったり割り当てたりするための text_contentget_root_node()has_child_nodes() は一般的な構造的質問に直接答えます。

フラグメントと隣接マークアップの解析

HTMLDocument.parse() は完全なページを処理し、HTMLDocument.parse_fragment() は部分的なマークアップを処理します。既存の要素に対して外科的に挿入する場合、Elementinsert_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 for Python は MIT ライセンスです — 商用利用、改変、再配布が無料です。コードは GitHub にあり、リリースは PyPI に aspose-html-foss として公開されます。


はじめに

関連リソース