使用 Aspose.HTML 在 Python 中创建文档 – 创建或加载 HTML、SVG、MHTML、EPUB

本文详细介绍了如何使用 Aspose.HTML for Python 通过 .NET API 创建 HTML 文档。API 提供了 HTMLDocument 类,该类是 HTML 层次结构的根,保存着整个内容。该类有一组构造函数,允许您以不同的方式创建或加载 HTML 文档。HTML 文档可以从头开始创建,比如创建一个带有 HTML 结构的空文档、从字符串创建、从内存流创建、从文件或 URL 加载。

HTML 文件

HTMLDocument 是 Aspose.HTML Python 库的起点。您可以通过使用其中一个HTMLDocument() 构造函数将 HTML 文档加载到**文档对象模型(DOM)**中,然后以编程方式读取、修改文档树、添加和删除节点、更改文档中的节点属性,正如官方规范中所描述的那样。

HTMLDocument “类提供了HTML DOM的内存表示,完全符合 W3C DOMWHATWG DOM规范。如果您熟悉 WHATWG DOM、 WHATWG HTMLJavaScript 标准,那么通过 .NET API 使用 Aspose.HTML for Python 将会非常轻松自如。

创建一个空的 HTML 文档

下面的 Python 代码片段展示了如何使用默认的 HTMLDocument() 构造函数来创建一个空的 HTML 文档并将其保存到文件中。

 1# Create an empty HTML document using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Setup an output directory and prepare a path to save the document
 7output_dir = "output"
 8if not os.path.exists(output_dir):
 9    os.makedirs(output_dir)
10save_path = os.path.join(output_dir, "document-empty.html")
11
12# Initialize an empty HTML document
13document = ah.HTMLDocument()
14
15# Work with the document here...
16
17# Save the document to a file
18document.save(save_path)

创建完成后,document-empty.html 文件将显示初始文档结构:空文档包括 <html>``<head><body>等元素。一旦创建了文档对象,以后就可以用 HTML 元素来填充它。

创建新的 HTML 文档

如果要以编程方式从头开始创建 HTML 文档,请使用不带参数的构造函数,如下代码片段所示:

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

在新文档中,我们使用 create_text_node() 方法创建了一个文本节点,给定了指定的字符串,并使用 append_child() 方法将其添加到<body>元素中。

编辑 HTML 文件的方法详见 编辑 HTML 文档一文。

有关保存 HTML 文件的更多详情,请参阅 保存 HTML 文档 一文。

从文件加载 HTML

如果您需要从文件中加载现有的 HTML 文件,并进行处理和保存,那么下面的代码片段将对您有所帮助:

 1# Load HTML from a file using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Setup directories and define paths
 7output_dir = "output/"
 8input_dir = "data/"
 9if not os.path.exists(output_dir):
10    os.makedirs(output_dir)
11
12document_path = os.path.join(input_dir, "document.html")
13save_path = os.path.join(output_dir, "document-edited.html")
14
15# Initialize a document from a file
16document = ah.HTMLDocument(document_path)
17
18# Work with the document
19
20# Save the document to a file
21document.save(save_path)

在上面的示例中,Python 代码为从 “data “目录读取 HTML 文档和将编辑后的文档保存到 “output “目录设置了目录和路径。它从指定文件初始化 HTML 文档,对其进行处理,然后将编辑后的文档保存到指定的输出路径。

从 URL 加载 HTML

互联网最常用的功能之一就是在用户的本地设备上选择文件并与之交互。在接下来的 Python 代码片段中,您可以看到如何将网页加载到 HTMLDocument 中。

如果您传递了一个错误的 URL,而该 URL 目前无法访问,程序库会抛出带有专用代码 “NetworkError “的 PlatformException,通知您无法找到所选资源。

1# Load HTML from a URL using Python
2
3import aspose.html as ah
4
5# Load a document from the specified web page
6document = ah.HTMLDocument("https://docs.aspose.com/html/files/aspose.html")
7
8# Write the document content to the output stream
9print(document.document_element.outer_html)

在上面的示例中,我们指定从 URL 加载 document.html 文件。

从 HTML 代码加载

如果您的 HTML 代码中包含链接资源(样式、脚本、图片等),则需要向文档的构造函数传递一个有效的 base_uri 参数。它将用于在文档加载过程中解析资源的位置。

从字符串加载 HTML

您可以使用 HTMLDocument() 构造函数之一从字符串内容创建文档。如果您想直接在代码中根据用户字符串创建文档并将其保存到文件中,下面的示例可以帮到您。我们创建一个包含文本 “Hello, World!” 的 HTML 文档。

 1# Create HTML from a string using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare HTML code
 7html_code = "<p>Hello, World!</p>"
 8
 9# Setup output directory
10output_dir = "output"
11if not os.path.exists(output_dir):
12    os.makedirs(output_dir)
13
14# Initialize a document from the string variable
15document = ah.HTMLDocument(html_code, ".")
16
17# Save the document to disk
18document.save(os.path.join(output_dir, "create-html-from-string.html"))

从数据流中加载 HTML

如果将 HTML 代码准备为内存中的 io.BytesIO 对象,则无需将其保存到文件中,只需将 HTML 代码传入专门的构造函数即可。在下面的示例中,为了从数据流中创建 HTML 文档,我们将使用 HTMLDocument(content, base_uri)构造函数:

 1# Load HTML from a stream using Python
 2
 3import os
 4import io
 5import aspose.html as ah
 6
 7# Prepare an output path for saving the document
 8output_dir = "output"
 9if not os.path.exists(output_dir):
10    os.makedirs(output_dir)
11
12# Use BytesIO instead of StringIO
13content_stream = io.BytesIO(b"<p>Hello, World!</p>")
14base_uri = "."
15# config = Configuration()
16
17# Initialize a document from the content stream
18document = ah.HTMLDocument(content_stream, base_uri)
19
20# Save the document to a disk
21document.save(os.path.join(output_dir, "load-from-stream.html"))

io.BytesIO 创建一个完全位于内存中的流对象。这对于无需写入磁盘的临时数据存储非常有用。

SVG 文档

可缩放矢量图形(SVG)是 W3C 标准的一部分,可以嵌入 HTMLDocument 中;我们根据官方 SVG2 规范 实现了具有完整 SVG 功能的 SVGDocument 类。这样,您就可以按照标准加载、读取和处理 SVG 文档了。

由于 “SVGDocument “和 “HTMLDocument “都基于相同的 WHATWG DOM标准,因此这两类文档的加载、读取、编辑、转换和保存等操作都是相似的。因此,任何演示操作 HTMLDocument 的示例也适用于 SVGDocument

你可以使用适当的 SVGDocument() 构造函数从字符串内容创建文档。如果您想从内存中的 content_stream 变量加载一个 SVG 文档,而不需要将其保存到文件中,下面的示例展示了如何做到这一点:

 1# Load SVG from a string using Python
 2
 3import io
 4import aspose.html.dom.svg as ahsvg
 5
 6# Initialize an SVG document from a string object
 7svg_content = "<svg xmlns='http://www.w3.org/2000/svg'><circle cx='50' cy='50' r='40'/></svg>"
 8base_uri = "."
 9content_stream = io.BytesIO(svg_content.encode('utf-8'))
10
11document = ahsvg.SVGDocument(content_stream, base_uri)
12
13# Write the document content to the output stream
14print(document.document_element.outer_html)
15
16# Save the document to a disk
17document.save("load-from-stream.svg")

在上面的示例中,我们创建了一个 SVG 文档,其中包含一个半径为 50 像素的圆。您可以从 Aspose.SVG for Python via .NET 文档中了解有关使用 SVG 文档的更多信息。

MHTML 文档

MHTML 是一种用于归档网页的格式。它将网页的 HTML 内容以及所有相关资源(如 CSS、JavaScript、图像和音频文件)打包成一个文件。网络开发人员通常使用 MHTML 来保存网页快照,以便存档。Aspose.HTML Python 库仅支持将 MHTML 文件渲染/转换为各种输出格式。有关详细信息,请参阅 格式间转换 一文。

EPUB 文档

EPUB 是一种广泛支持的电子书和电子出版物格式,兼容大多数阅读设备,包括智能手机、平板电脑和电脑。与 MHTML 相似,Aspose.HTML 仅支持将 EPUB 文件渲染为各种输出格式。更多详情,请参阅 格式间转换一文。

另见

  • 下载 Aspose.HTML for Python via .NET库,成功、快速、轻松地处理您的 HTML 文档。Python 库可以创建、修改、提取数据、转换和渲染 HTML 文档,而无需外部软件。它支持 EPUB、MHTML、XML、SVG 和 Markdown 等流行文件格式,并可渲染为 PDF、DOCX、XPS 和图像文件格式。

  • 您可以从 GitHub 下载完整的示例和数据文件。

  • Aspose.HTML 提供免费的在线 HTML 转换器,用于将 HTML 文档转换为各种流行格式。只需从文件或 URL 中加载 HTML,选择要转换的格式,就大功告成了。它速度快,而且完全免费!

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.