Edit HTML Documents in Python

Aspose.HTML for Python via .NET represents HTML as a Document Object Model (DOM) tree. After creating or loading an HTMLDocument, you can create or remove nodes, update attributes and text, replace element markup, and change inline or internal CSS.

To edit HTML in Python, create or load an HTMLDocument, locate or create the required DOM node, modify it with methods such as create_element(), append_child(), or set_attribute(), and call save() to persist the result. Use inner_html when trusted markup should replace an element’s child content.

HTML DOM APIs for Editing

The DOM represents a document as a tree of nodes. The document is the root, elements define the structure, attributes describe elements, and text nodes hold character data. These concepts and operations are defined by the WHATWG DOM Standard. The aspose.html.dom module provides the core types used to inspect and modify that tree.

APIPurpose
DocumentRepresents the complete document tree and provides methods for creating nodes.
NodeRepresents one node and provides tree operations such as appending, inserting, and removing children.
ElementRepresents an element and provides access to attributes and serialized markup.
AttrRepresents an attribute associated with an element.

Common editing methods and properties include:

APIUse it to
create_element()Create an element with the specified tag name.
create_text_node()Create text that is not parsed as HTML markup.
query_selector()Return the first element that matches a CSS selector.
append_child()Add a node as the last child of another node.
insert_before()Insert a node before an existing child.
remove_child()Remove a child node from its parent.
set_attribute()Add an attribute or replace its value.
get_attribute()Read an attribute value.
inner_htmlGet or replace the markup inside an element.
outer_htmlGet the element’s own markup together with its descendants.

Edit Existing HTML and Create New Elements

You can apply the same DOM operations to a newly created document or an existing HTML file. To edit an existing file, pass its path to HTMLDocument, modify the loaded DOM, and save the document to the required output path. See Create and Load HTML Documents for loading examples.

Edit an Existing HTML File

The following example loads edit-document.html from the data directory, updates existing elements, and saves the edited document as output/edited-document.html:

  1. Prepare the input and output paths and create the output directory.
  2. Load the existing HTML file into an HTMLDocument.
  3. Find the heading and status paragraph with query_selector().
  4. Update the document title, heading text, paragraph text, and paragraph class.
  5. Save the modified DOM as output/edited-document.html.
 1# Edit an existing HTML file in Python
 2
 3import os
 4import aspose.html as ah
 5
 6data_dir = "data"
 7output_dir = "output"
 8os.makedirs(output_dir, exist_ok=True)
 9
10input_path = os.path.join(data_dir, "edit-document.html")
11output_path = os.path.join(output_dir, "edited-document.html")
12
13# Load and edit an existing HTML file
14with ah.HTMLDocument(input_path) as document:
15    heading = document.query_selector("h1")
16    status = document.query_selector("#status")
17
18    document.title = "Final Project Status"
19    heading.text_content = "Final Project Status"
20    status.text_content = "Approved"
21    status.set_attribute("class", "approved")
22
23    document.save(output_path)

The saved file contains the updated <title> and <h1> text. The status changes from Draft to Approved, and the existing .approved CSS rule displays it in bold green text.

Create Styled HTML with DOM Methods

The next example builds a document with an internal CSS rule and a styled paragraph:

  1. Create an empty HTMLDocument.
  2. Create a <style> element containing a .col color rule and append it to <head>.
  3. Create a paragraph, assign the col class, and append a text node.
  4. Append the paragraph to <body>.
  5. Save the result as output/edit-document.html.
 1# Create and add new HTML elements using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Define output directory and file paths
 7output_dir = "output/"
 8save_path = os.path.join(output_dir, "edit-document.html")
 9
10# Ensure the output directory exists
11os.makedirs(output_dir, exist_ok=True)
12
13# Create an instance of an HTML document
14document = ah.HTMLDocument()
15
16# Create a style element and set the teal color for elements with class "col"
17style = document.create_element("style")
18style.text_content = ".col { color: teal }"
19
20# Find the document head element and append the style element
21head = document.get_elements_by_tag_name("head")[0]
22head.append_child(style)
23
24# Create a paragraph <p> element with class "col"
25p = document.create_element("p")
26p.class_name = "col"
27
28# Create a text node
29text = document.create_text_node("Edit HTML document")
30
31# Append the text node to the paragraph
32p.append_child(text)
33
34# Append the paragraph to the document body
35document.body.append_child(p)
36
37# Save the HTML document to a file
38document.save(save_path)

This example saves HTML only. The two CSS examples later on the page additionally render their edited documents to PDF.

Creating an element does not insert it into the document automatically. The element becomes part of the saved DOM only after it is appended to a parent node, as shown when the example adds <style> to <head> and <p> to <body>.

Edit HTML with inner_html and outer_html

Use inner_html to get or replace the markup inside an element. Use outer_html to read the serialized markup of the element itself together with its descendants.

The following example:

  1. Creates an empty document and prints its initial root markup.
  2. Assigns a paragraph fragment to document.body.inner_html.
  3. Reads the paragraph’s inner_html.
  4. Prints the complete updated markup through document.document_element.outer_html.
 1# Edit HTML body content and get modified document as a string using Python
 2
 3import aspose.html as ah
 4
 5# Create an instance of an HTML document
 6document = ah.HTMLDocument()
 7
 8# Write the content of the HTML document to the console
 9print(document.document_element.outer_html)  # output: <html><head></head><body></body></html>
10
11# Set the content of the body element
12document.body.inner_html = "<p>HTML is the standard markup language for Web pages.</p>"
13
14# Find the document <p> element
15p = document.get_elements_by_tag_name("p")[0]
16
17# Write the updated content of the HTML document to the console
18print(p.inner_html)  # output: HTML is the standard markup language for Web pages.
19
20# Write the updated content of the HTML document to the console
21print(document.document_element.outer_html)  # output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>

Assigning inner_html parses the supplied string as markup and replaces all existing child nodes of the target element. Use text_content or create_text_node() when a value must remain plain text. This example prints the result to the console and does not save a file.

Edit CSS in an HTML Document

Use an element’s style attribute for declarations that apply to one element. Add a <style> element to the document <head> when CSS rules should target elements through selectors or class names.

Edit Inline CSS

The inline CSS example sets font size, font family, and text color on a paragraph, saves the edited HTML, and renders the same document to PDF:

  1. Create an HTMLDocument containing a paragraph.
  2. Retrieve the paragraph and set its style attribute.
  3. Save the document as output/edit-inline-css.html.
  4. Create a PdfDevice and call render_to() to produce output/edit-inline-css.pdf.
 1# How to set inline CSS styles in an HTML element using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.rendering.pdf as rp
 6
 7# Define the content of the HTML document
 8content = "<p>Edit inline CSS using Aspose.HTML for Python via .NET</p>"
 9
10# Create an instance of an HTML document with specified content
11document = ah.HTMLDocument(content, ".")
12
13# Find the paragraph element and set a style attribute
14paragraph = document.get_elements_by_tag_name("p")[0]
15paragraph.set_attribute("style", "font-size: 150%; font-family: arial; color: teal")
16
17# Save the HTML document to a file
18output_dir = "output/"
19os.makedirs(output_dir, exist_ok=True)
20html_path = os.path.join(output_dir, "edit-inline-css.html")
21document.save(html_path)
22
23# Create an instance of the PDF output device and render the document to this device
24pdf_path = os.path.join(output_dir, "edit-inline-css.pdf")
25with rp.PdfDevice(pdf_path) as device:
26    document.render_to(device)
Example-EditInlineCss.py hosted with ❤ by GitHub

The rendered paragraph uses a 150% font size, Arial when that font is available, and teal text:

Paragraph rendered in teal with inline CSS

Edit Internal and Inline CSS

The final example combines class rules in a <style> element with inline declarations on individual elements:

  1. Create an HTMLDocument containing a heading and paragraph.
  2. Create a <style> element with .frame1 and .frame2 rules and append it to <head>.
  3. Assign the classes to the heading and paragraph.
  4. Add inline declarations that supplement or override the class rules.
  5. Save output/edit-internal-css.html and render output/edit-internal-css.pdf.
 1# Edit HTML with internal CSS using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.rendering.pdf as rp
 6
 7
 8# Define the content of the HTML document
 9content = "<div><h1>Internal CSS</h1><p>An internal CSS is used to define a style for a single HTML page</p></div>"
10
11# Create an instance of an HTML document with specified content
12document = ah.HTMLDocument(content, ".")
13
14# Create a <style> element and define internal CSS rules
15style = document.create_element("style")
16style.text_content = (
17    ".frame1 { margin-top:50px; margin-left:50px; padding:25px; width:360px; height:90px; "
18    "background-color:#82011a; font-family:arial; color:#fff5ee;} \r\n"
19    ".frame2 { margin-top:-70px; margin-left:160px; text-align:center; padding:20px; width:360px; "
20    "height:100px; background-color:#ebd2d7;}"
21)
22
23# Find the <head> element and append the style element
24head = document.get_elements_by_tag_name("head")[0]
25head.append_child(style)
26
27# Find the heading element and apply styles
28header = document.get_elements_by_tag_name("h1")[0]
29header.class_name = "frame1"
30
31# Update the style using the style attribute directly
32header.set_attribute("style", "font-size: 200%; text-align: center;")
33
34# Find the paragraph element and apply styles
35paragraph = document.get_elements_by_tag_name("p")[0]
36paragraph.class_name = "frame2"
37paragraph.set_attribute("style", "color: #434343; font-size: 150%; font-family: verdana;")
38
39# Save the HTML document to a file
40output_dir = "output"
41os.makedirs(output_dir, exist_ok=True)
42html_path = os.path.join(output_dir, "edit-internal-css.html")
43document.save(html_path)
44
45# Create an instance of the PDF output device and render the document to this device
46pdf_path = os.path.join(output_dir, "edit-internal-css.pdf")
47with rp.PdfDevice(pdf_path) as device:
48    document.render_to(device)

The rendered PDF applies the internal class rules together with the inline font size, alignment, color, and font-family declarations:

Heading and paragraph rendered with internal and inline CSS

Common HTML Editing Issues

IssueLikely CauseRecommended Action
A created element is missing from the outputThe element was created but not attached to the document tree.Append it to document.body or another parent node before saving.
Existing children disappear after assigning inner_htmlSetting inner_html replaces all current child markup.Use append_child() when existing children must be preserved.
HTML tags appear as visible textThe value was assigned as text content rather than parsed markup.Use inner_html only when trusted markup should become DOM nodes.
A CSS class rule is not appliedThe <style> element is not in the document, the class name does not match, or an inline declaration overrides the rule.Check the DOM location, selector, class name, and CSS cascade.
Changes are missing from the output fileThe document was changed in memory but not saved afterward.Call save() after completing all DOM and CSS changes.

Other Platforms

Related Articles