Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created August 5, 2026 07:04
Show Gist options
  • Select an option

  • Save aspose-com-gists/133fdf72e89fa1f47f8c93811b46f43e to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/133fdf72e89fa1f47f8c93811b46f43e to your computer and use it in GitHub Desktop.
Create Read and Edit HTML in Python

Create Read and Edit HTML in Python

This tutorial shows Python developers how to create, read, and edit HTML files with Aspose.HTML for Python via .NET. You'll learn prerequisites, code examples, configuration options, performance tuning, and validation techniques for building content tools.

Read the full guide here: https://blog.aspose.com/html/create-read-and-edit-html-in-python/

import os
import sys
from aspose.html import HtmlDocument, HtmlLoadOptions, HtmlSaveOptions, HtmlLoadOptions
def create_html(output_path: str):
# Create a new empty HTML document
doc = HtmlDocument()
try:
# Build <html><head><title>...</title></head><body>...</body></html>
html = doc.create_element("html")
doc.append_child(html)
head = doc.create_element("head")
html.append_child(head)
title = doc.create_element("title")
title.inner_html = "Sample Document"
head.append_child(title)
body = doc.create_element("body")
html.append_child(body)
h1 = doc.create_element("h1")
h1.id = "mainHeader"
h1.inner_html = "Welcome to Aspose.HTML"
body.append_child(h1)
p = doc.create_element("p")
p.inner_html = "This document was generated programmatically."
body.append_child(p)
# Save with pretty printing for readability
save_opts = HtmlSaveOptions()
save_opts.pretty_print = True
doc.save(output_path, save_opts)
finally:
doc.dispose()
def read_and_edit_html(input_path: str, output_path: str):
load_opts = HtmlLoadOptions()
# Enable lazy loading of external resources for large files
load_opts.resource_loading = HtmlLoadOptions.ResourceLoadingMode.LAZY
doc = HtmlDocument(input_path, load_opts)
try:
# Edit the <title> element if it exists
title_elem = doc.get_elements_by_tag_name("title")
if title_elem.length > 0:
title_elem.item(0).inner_html = "Edited Document Title"
# Change header text by id
header = doc.get_element_by_id("mainHeader")
if header:
header.inner_html = "Edited Header via Aspose.HTML"
# Append a new paragraph at the end of <body>
body = doc.get_elements_by_tag_name("body").item(0)
if body:
new_para = doc.create_element("p")
new_para.inner_html = "Additional paragraph added during edit."
body.append_child(new_para)
# Insert a new <div> with a class attribute
new_div = doc.create_element("div")
new_div.set_attribute("class", "highlight")
new_div.inner_html = "<strong>Important notice:</strong> This is a dynamically inserted div."
body.append_child(new_div)
# Save edited HTML with compression disabled for faster I/O on large files
save_opts = HtmlSaveOptions()
save_opts.compression = HtmlSaveOptions.CompressionMode.NONE
doc.save(output_path, save_opts)
finally:
doc.dispose()
def validate_edited_html(file_path: str):
doc = HtmlDocument(file_path)
try:
# Simple validation: ensure the edited header exists and contains expected text
header = doc.get_element_by_id("mainHeader")
if not header:
raise ValueError("Validation failed: 'mainHeader' element missing.")
if "Edited Header" not in header.inner_html:
raise ValueError("Validation failed: Header text was not updated correctly.")
# Ensure the newly added div exists
divs = doc.get_elements_by_class_name("highlight")
if divs.length == 0:
raise ValueError("Validation failed: Highlight div not found.")
print("Validation succeeded: edited HTML structure is as expected.")
finally:
doc.dispose()
def main():
# Paths (use generic names; adjust as needed)
created_path = os.path.abspath("created.html")
input_path = os.path.abspath("input.html") # Assume this file exists
edited_path = os.path.abspath("edited.html")
try:
# Step 1: Create a new HTML file
create_html(created_path)
print(f"Created HTML saved to: {created_path}")
# Step 2: Read existing HTML and edit it
if not os.path.isfile(input_path):
raise FileNotFoundError(f"Input HTML file not found: {input_path}")
read_and_edit_html(input_path, edited_path)
print(f"Edited HTML saved to: {edited_path}")
# Step 3: Validate the edited HTML
validate_edited_html(edited_path)
except Exception as e:
# Centralized error handling
print(f"An error occurred: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment