프로그램적으로 HTML 파일을 조작하는 것은 동적 웹 콘텐츠 도구 및 편집기를 구축하는 데 필수적입니다. Aspose.HTML for Python via .NET은 표준 기반 DOM 구현을 제공하여 브라우저 없이, 정규식 없이도 처음부터 문서를 만들고, 기존 마크업을 검사하며, 이를 다시 작성할 수 있게 해줍니다. 이 가이드는 작업을 create, read, edit라는 세 가지 집중 섹션으로 나누며, 각각 실행 가능한 예제가 포함되어 있습니다. 끝까지 진행하면 Python 기반 콘텐츠 파이프라인에 삽입할 수 있는 재사용 가능한 워크플로우를 얻게 됩니다.

시작하기 전에: 전제 조건 및 설치

이 튜토리얼을 따라하려면 다음이 필요합니다:

  • 개발 머신에 Python 3.8 이상이 설치되어 있어야 합니다.
  • 64비트 OS(Windows, Linux 또는 macOS) — 패키지는 네이티브 .NET 바이너리를 포함합니다.
  • 유효한 Aspose.HTML for Python via .NET 라이선스(임시 라이선스 제공 가능).

pip으로 SDK를 설치합니다:

pip install aspose-html-net

최신 바이너리를 직접 download page에서 다운로드할 수 있습니다. 설치 후, 필요한 타입을 가져오세요:

from aspose.html import HTMLDocument
from aspose.html.saving import HTMLSaveOptions

라이선스 파일이 있는 경우, 애플리케이션 시작 시 한 번 적용하면 출력이 평가 제한 없이 자유로워집니다:

from aspose.html import License

license = License()
license.set_license("Aspose.HTML.Python.lic")

SDK가 준비되었으니, 세 가지 핵심 작업을 진행해 보겠습니다.

단계별 구축: Python에서 HTML 읽기 및 편집

Python에서 HTML 문서 만들기

HTMLDocument는 이미 html, head, body 골격을 포함하고 있으므로 즉시 노드를 추가할 수 있습니다. 요소는 create_element()로 생성되고, 텍스트 노드는 create_text_node()로 생성되며, 두 경우 모두 append_child()로 트리에 연결됩니다.

from aspose.html import HTMLDocument

# An empty document already has <html>, <head>, and <body>
document = HTMLDocument()
document.title = "Sample Document"

# <h1 id="mainHeader">Welcome to Aspose.HTML</h1>
header = document.create_element("h1")
header.set_attribute("id", "mainHeader")
header.append_child(document.create_text_node("Welcome to Aspose.HTML"))
document.body.append_child(header)

# <p>This document was generated programmatically.</p>
paragraph = document.create_element("p")
paragraph.text_content = "This document was generated programmatically."
document.body.append_child(paragraph)

document.save("created.html")

각 노드가 문서를 통해 생성되기 때문에, 결과 마크업은 항상 올바르게 형성됩니다 — 수동 태그 균형 맞추기나 문자열 연결이 필요 없습니다.

Python을 사용하여 기존 HTML 문서 읽기

파일 경로를 HTMLDocument 생성자에 전달하면 Aspose.HTML이 파일을 실시간 DOM 트리로 파싱합니다. 그 후 브라우저에서와 같이 id, 태그 이름 또는 CSS 선택자를 사용하여 쿼리할 수 있습니다.

from aspose.html import HTMLDocument

document = HTMLDocument("created.html")
print("Title:", document.title)

# Look up a single element by its id
header = document.get_element_by_id("mainHeader")
if header is not None:
    print("Header:", header.text_content)

# Iterate over every paragraph in the document
paragraphs = document.get_elements_by_tag_name("p")
for index in range(paragraphs.length):
    print(f"Paragraph {index}:", paragraphs[index].text_content)

# CSS selectors work too
for link in document.query_selector_all("a[href]"):
    print("Link:", link.get_attribute("href"))

# Serialize the whole tree back to markup when you need the raw HTML
print(document.document_element.outer_html)

이미 메모리에 있는 마크업을 콘텐츠와 기본 URI를 함께 전달하여 구문 분석할 수도 있습니다. 이는 HTML이 API 응답으로 도착할 때 편리합니다:

content = "<html><body><p>Loaded from a string.</p></body></html>"
document = HTMLDocument(content, ".")

Python을 사용하여 기존 HTML 문서 편집

편집은 단순히 DOM 변형입니다: text_content 또는 inner_html에 할당하고, set_attribute()로 속성을 변경하고, append_child()로 노드를 삽입하며, remove_child()로 노드를 제거합니다. 완료되면 결과를 저장하세요.

from aspose.html import HTMLDocument

document = HTMLDocument("created.html")
# 1. Update the document title
document.title = "Edited Document Title"

# 2. Replace the header text
header = document.get_element_by_id("mainHeader")
if header is not None:
    header.text_content = "Edited Header via Aspose.HTML"

# 3. Insert a highlighted notice block
notice = document.create_element("div")
notice.set_attribute("class", "highlight")
notice.inner_html = "<strong>Important notice:</strong> This div was inserted at runtime."
document.body.append_child(notice)

# 4. Remove the first paragraph
paragraphs = document.get_elements_by_tag_name("p")
if paragraphs.length > 0:
    obsolete = paragraphs[0]
    obsolete.parent_node.remove_child(obsolete)

document.save("edited.html")

이 세 가지 작업은 깔끔하게 구성됩니다: 한 번 생성하고, 검사가 필요할 때마다 읽으며, 내용이 변경될 때마다 자주 편집합니다.

참고: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에서 사용하기 전에 파일 경로(created.html, edited.html 등)를 실제 파일 위치에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인한 다음 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에 문의하십시오.

결론

Python에서 HTML 파일을 만들고, 읽고, 편집하는 것이 Aspose.HTML for Python via .NET을 사용하면 간단해집니다. 각 작업은 익숙한 DOM 관용구에 매핑됩니다: create_element() 로 노드를 만들고, get_element_by_id()query_selector_all() 로 조회하며, text_content, inner_html, set_attribute() 로 변형한 다음 save() 로 저장합니다. 프로덕션 사용을 위해 적절한 라이선스를 획득해야 함을 기억하세요; 가격 세부 정보는 제품 페이지에서 확인할 수 있으며, 임시 라이선인은 임시 라이선스 페이지에서 얻을 수 있습니다. SDK를 사용하면 이제 어떤 Python 기반 애플리케이션에도 원활하게 통합되는 강력한 HTML 조작 도구를 구축할 수 있습니다.

FAQs

  • Python에서 Aspose.HTML을 사용하여 HTML 파일을 만드는 방법은?HTMLDocument를 인스턴스화하고, create_element()create_text_node()로 노드를 만든 다음, append_child()로 연결하고, document.save("created.html")를 호출합니다. 위의 생성 예제는 전체 순서를 보여줍니다.

  • 기존 HTML 파일의 내용을 어떻게 읽나요? 파일 경로를 HTMLDocument 생성자에 전달한 다음, get_element_by_id(), get_elements_by_tag_name(), 또는 query_selector_all()을 사용하여 DOM을 쿼리합니다. 값은 text_content, inner_html, 및 get_attribute()를 통해 사용할 수 있습니다.

  • HTML 문서를 편집하고 변경 사항을 저장하려면 어떻게 해야 하나요? 문서를 로드하고, text_content 또는 inner_html에 할당한 뒤, set_attribute()로 속성을 변경하고, append_child()로 노드를 추가하며, remove_child()로 노드를 제거합니다. 그런 다음 document.save()를 호출하고, 필요에 따라 HTMLSaveOptions 인스턴스를 전달합니다.

  • 더 많은 예제, 문서 및 지원을 어디서 찾을 수 있나요? 공식 문서에서는 자세한 가이드를 제공하고, API 참조에서는 모든 클래스와 멤버를 확인할 수 있으며, 커뮤니티는 Aspose.HTML 포럼을 통해 접할 수 있습니다.

Read More