소개

DOM 레이어는 Python용 Aspose.HTML FOSS의 핵심입니다. 표준이 하는 방식대로 HTML 페이지를 Document, Element, Text, Comment, DocumentFragment 노드들의 트리로 모델링하며 — 브라우저 없이 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_nodes, parent_node, first_child을, 서브트리의 텍스트를 읽거나 할당하기 위해 text_content을 사용합니다. get_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으로 게시됩니다.


시작하기

관련 리소스