Save HTML Documents in Python

After creating, loading, or editing an HTMLDocument, call save() to write its current DOM state to a file. Aspose.HTML for Python via .NET can save HTML, create MHTML or Markdown output, and save standalone SVG documents.

To save HTML in Python, create or load an HTMLDocument, modify it if needed, and call document.save(path). Use HTMLSaveOptions to control linked resources, or pass HTMLSaveFormat.MHTML or HTMLSaveFormat.MARKDOWN to select another HTML-based output format.

Saving and conversion solve different tasks:

APIUse it to
HTMLDocument.save()Save the current HTML document by using a supported path, format, options, or resource handler overload.
HTMLSaveOptionsConfigure HTML output and access linked-resource handling settings.
ResourceHandlingOptionsControl how resources and linked pages are processed during saving.
HTMLSaveFormatSelect MHTML or Markdown output with a format-based save() overload.
SVGDocumentCreate, edit, and save a standalone SVG document.

Save HTML to a File

The simplest workflow creates an HTML document, adds content to its DOM, and saves the result as a local .html file.

The following example:

  1. Creates the output directory and the save-html-document.html destination path.
  2. Initializes an empty HTMLDocument.
  3. Creates a Hello, World! text node and appends it to the document body.
  4. Calls save() to write the document to the HTML file.
 1# Save HTML to a file using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare an output path for saving the document
 7output_dir = "output"
 8if not os.path.exists(output_dir):
 9    os.makedirs(output_dir)
10
11document_path = os.path.join(output_dir, "save-html-document.html")
12
13# Initialize an empty HTML document
14with ah.HTMLDocument() as document:
15    # Create a text node and add it to the document
16    text = document.create_text_node("Hello, World!")
17    document.body.append_child(text)
18
19    # Save HTML to a file
20    document.save(document_path)

The HTMLDocument() constructor creates the document structure in memory. Changes remain in memory until save() writes the current DOM to the destination. To load and modify an existing file before saving it, see Edit HTML Documents in Python.

Save HTML with Linked Resources

For examples of saving CSS and images to a selected folder, embedding resources in one HTML file, and processing directly linked pages, see Save HTML with Resources in Python.

Save HTML as MHTML or Markdown

The HTMLSaveFormat enumeration selects MHTML or Markdown when calling a compatible save() overload.

Save HTML to MHTML

MHTML is a web archive format that combines the current HTML document and handled resources in one file. A linked HTML page is not included merely because it appears in an <a href> element; linked-page processing is controlled by max_handling_depth and URL restrictions.

The following example:

  1. Creates document.html and a page named linked-file.html.
  2. Loads document.html into an HTMLDocument.
  3. Calls save() with HTMLSaveFormat.MHTML.
  4. Creates output/save-html-to-mhtml.mht containing the current document and resources handled under the active save settings.
 1# Save HTML as MHTML using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.saving as sav
 6
 7# Define the output directory and document path
 8output_dir = 'output'
 9document_path = os.path.join(output_dir, 'save-html-to-mhtml.mht')
10
11# Ensure the output directory exists
12os.makedirs(output_dir, exist_ok=True)
13
14# Prepare a simple HTML file with a linked document
15with open('document.html', 'w') as file:
16    file.write("<p>Hello, World!</p>"
17               "<a href='linked-file.html'>linked file</a>")
18
19# Prepare a simple linked HTML file
20with open('linked-file.html', 'w') as file:
21    file.write("<p>Hello, linked file!</p>")
22
23# Load the "document.html" into memory
24with ah.HTMLDocument('document.html') as document:
25    # Save the document to MHTML format
26    document.save(document_path, sav.HTMLSaveFormat.MHTML)

With the default page depth of 0, the example does not package the target of the linked-file.html hyperlink as another archived page. Use MHTMLSaveOptions when linked-page depth or resource handling requires additional configuration.

Save HTML to Markdown

Markdown is a plain-text markup format suited to editable documentation and content workflows.

The following example:

  1. Loads data/document.html into an HTMLDocument.
  2. Selects output/html-to-markdown.md as the destination.
  3. Calls save() with HTMLSaveFormat.MARKDOWN.
  4. Writes the document content in Markdown format.
 1# Save HTML as Markdown using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.saving as sav
 6
 7# Prepare a path to a source and output HTML file
 8data_dir = "data"
 9output_dir = "output"
10if not os.path.exists(output_dir):
11    os.makedirs(output_dir)
12
13input_path = os.path.join(data_dir, "document.html")
14output_path = os.path.join(output_dir, "html-to-markdown.md")
15
16# Load the HTML document from a file
17document = ah.HTMLDocument(input_path)
18
19# Save the document to Markdown format
20document.save(output_path, sav.HTMLSaveFormat.MARKDOWN)

For converter-based workflows and additional Markdown settings, see Convert HTML to Markdown in Python.

Save an SVG Document

SVG can be embedded in HTML or processed as a standalone XML-based vector document. Use SVGDocument for a standalone SVG DOM. HTML and SVG use the node concepts defined by the WHATWG DOM Standard, while the SVG 2 specification defines SVG elements and rendering behavior.

The following example:

  1. Defines SVG markup containing a group of paths.
  2. Creates an SVGDocument from the markup and a base URI.
  3. Creates the output directory.
  4. Saves the vector document as output/save-html-to-svg.svg.
 1# Create and save SVG document using Python
 2
 3import os
 4import aspose.html.dom.svg as ahsvg
 5
 6# Define the output directory and document path
 7output_dir = 'output'
 8document_path = os.path.join(output_dir, 'save-html-to-svg.svg')
 9
10# Ensure the output directory exists
11os.makedirs(output_dir, exist_ok=True)
12
13# Prepare SVG code
14svg_code = """
15<svg xmlns='http://www.w3.org/2000/svg' height='400' width='300'>
16    <path stroke="#a06e84" stroke-width="3" fill="#74aeaf" d="  
17	M 150,50 L 150, 300
18	M 120,100 L 150,50 L 180, 100
19    M 110,150 L 150,90 L 190, 150
20	M 90,220 L 150,130 L 210, 220
21	M 70,300 L 150,190 L 230, 300
22    M 110,310 L 150,240 L 190, 310
23	" />
24</svg>
25"""
26
27# Initialize an SVG instance from the content string
28document = ahsvg.SVGDocument(svg_code, '.')
29
30# Save SVG
31document.save(document_path)

This workflow creates and saves SVG source content; it does not convert an HTML page to SVG. For additional SVG workflows, see the Aspose.SVG for Python via .NET documentation.

Common HTML Saving Issues

IssueCause and recommended action
Images, CSS, scripts, or fonts are missingCheck the base URL, resource paths, handling behavior, and URL restrictions configured through HTMLSaveOptions.
A linked HTML page is not processedThe default max_handling_depth is 0. Use 1 for directly referenced pages or another suitable depth, subject to URL restrictions.
A PDF, DOCX, XPS, or image was expected from save()HTMLDocument.save() handles HTML-based formats. Use the HTML conversion or rendering APIs for visual output formats.
MHTML or Markdown output was not createdPass HTMLSaveFormat.MHTML or HTMLSaveFormat.MARKDOWN to the compatible save() overload.
SVG changes are absent from the outputApply the changes to an SVGDocument and call its save() method afterward.

FAQ

How do I save an HTML document in Python?

Create or load an HTMLDocument, modify its DOM if needed, and call document.save(path) to write the current document state to an HTML file.

Does saving HTML include images and CSS?

The save API can process linked resources. Use HTMLSaveOptions.resource_handling_options to control the handling behavior and which resource URLs may be processed.

How do I save HTML and resources as a single file?

To create a self-contained .html file, set HTMLSaveOptions.resource_handling_options.default to ResourceHandling.EMBED and configure JavaScript separately when required. To create a MIME web archive, call document.save(path, HTMLSaveFormat.MHTML). See Save HTML with Resources in Python for a complete embedding example.

What is the difference between saving and converting HTML?

Saving writes the document to an HTML-based format such as HTML, MHTML, or Markdown. Conversion produces another representation such as PDF, DOCX, XPS, or an image.

Other Platforms

Related Articles