以程式方式操作 HTML 檔案對於構建動態網頁內容工具和編輯器至關重要。 Aspose.HTML for Python via .NET 提供基於標準的 DOM 實作,讓您能從頭建立文件、檢查現有標記,並重新寫入——全部不需要瀏覽器,也不需要正則表達式。本指南將工作分為三個重點部分:createreadedit,每個部分都有可執行的範例。完成後,您將擁有一個可重用的工作流程,可嵌入任何基於 Python 的內容管線中。

開始之前:先決條件與安裝

要遵循本教程,您需要:

  • 在開發機器上安裝了 Python 3.8 或更新版本。
  • 64 位元作業系統(Windows、Linux 或 macOS)— 此套件隨附原生 .NET 二進位檔。
  • 有效的 Aspose.HTML for Python via .NET 授權(可提供臨時授權)。

使用 pip 安裝 SDK:

pip install aspose-html-net

您也可以直接從下載頁面下載最新的二進位檔。安裝完成後,匯入您需要的類型:

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 已經包含 htmlheadbody 骨架,因此您可以立即開始追加節點。元素由 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_contentinner_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.htmledited.html 等)以符合實際檔案位置,驗證所有必要的相依性已正確安裝,並在開發環境中徹底測試。 若遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。

結論

在 Python 中創建、讀取和編輯 HTML 文件變得簡單,這得益於 Aspose.HTML for Python via .NET。每個操作都映射到熟悉的 DOM 慣例:使用 create_element() 建立節點,使用 get_element_by_id()query_selector_all() 查詢節點,通過 text_contentinner_htmlset_attribute() 變更它們,最後使用 save() 保存。請記得為生產環境獲取適當的許可證;產品頁面上提供了價格細節,臨時許可證可從 臨時許可證頁面 獲得。有了 SDK,您現在可以構建穩健的 HTML 操作工具,無縫集成到任何基於 Python 的應用程序中。

常見問題

  • 如何在 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_contentinner_htmlget_attribute() 取得值。

  • 如何編輯 HTML 文件並保存更改? 載入文件,將其指派給 text_contentinner_html,使用 set_attribute() 變更屬性,使用 append_child() 新增節點,並使用 remove_child() 移除節點。然後呼叫 document.save(),可選地傳遞 HTMLSaveOptions 實例。

  • 我可以在哪裡找到更多範例、文件和支援?
    官方文件(官方文件)提供詳細的指南,API 參考(API 參考)列出所有類別和成員,社群可透過 Aspose.HTML 論壇 取得聯繫。

閱讀更多