用 Python 保存 HTML 文档
如何用 Python 保存 HTML
本文详细介绍了如何使用 Aspose.HTML for Python 通过 .NET API 保存 HTML 文档。使用 HTML 文档后,您可以使用 HTMLDocument.save() 方法之一保存更改。有一些方法可以将文档保存到文件或 URL。
- Aspose.HTML Python API 提供了包含 SaveOptions 和 ResourceHandlingOptions 类的 aspose.html.saving 命名空间,允许您设置保存操作的选项。
- Aspose.HTML for Python via .NET 提供了 aspose.html.saving.resourcehandlers 命名空间,其中包含负责处理资源的 ResourceHandler 和 FileSystemResourceHandler 类。
请注意,Aspose.HTML for Python via .NET 为创建输出文件提供了两种不同的方法:
基于 HTML 的方法:这种方法的输出是类似 HTML 的文件。它使用 SaveOptions 类,该类是管理脚本、样式和图像等相关资源保存过程的基础。ResourceHandler 类负责处理这些资源。它的开发目的是将 HTML 内容和相关资源保存到数据流中,并提供一些方法让您控制资源的处理过程。
可视化表示法:这种方法侧重于创建 HTML 的可视化表示。它基于 RenderingOptions 类,该类提供了定义页面大小、页边距、分辨率、用户样式等的专门方法。
本文将介绍 SaveOptions 和 ResourceHandler 类的使用。
保存 HTML
完成对 HTML 文档的修改后,您可能想保存它。您可以使用 HTMLDocument 类提供的 save() 方法之一来实现。下面是一个保存 HTML 文件的简单 Python 示例:
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)在上面的示例中,我们使用 HTMLDocument() 构造函数来初始化一个空的 HTML 文档。HTMLDocument 类的
create_text_node(data) 方法会根据指定的字符串创建一个文本节点。调用 document.save(document_path) 时,该方法会将 document 对象的 HTML 内容写入由 document_path 指定的文件。
上面的示例非常简单。不过,在实际应用中,您往往需要对保存过程进行额外的控制。接下来的几节将介绍如何使用资源处理选项或将文档保存为不同格式。
保存选项和资源处理选项
SaveOptions 是一个基类,允许为保存操作指定附加选项,并有助于管理链接的资源。SaveOptions 类的 resource_handling_options 属性用于配置资源处理。ResourceHandlingOptions 类定义了管理 HTML 文档关联资源的选项。它提供了多个属性,用于控制在保存或处理文档时如何处理各种类型的资源:
- java_script 属性决定了 JavaScript 资源的管理方式。它可以保存为分离的链接文件,也可以嵌入 HTML 文件,甚至可以被忽略。默认值为
ResourceHandling.SAVE。 - 默认属性设置所有资源的默认处理方法。默认值是
ResourceHandling.SAVE。 - resource_url_restriction 属性定义了 CSS、JavaScript 和图像等资源的 URL 限制。默认值是
UrlRestriction.SAME_HOST,它将资源限制为与文档托管在同一域上的资源。 - page_url_restriction属性用于指定页面的 URL 限制。默认值为
UrlRestriction.ROOT_AND_SUB_FOLDERS,即只处理根目录及其子文件夹中的页面。 - max_handling_depth 属性控制页面处理的最大深度。深度为 1 表示只处理保存文档中直接引用的页面。将此属性设置为-1,将处理所有页面。默认值为 0,表示只处理文档本身。
将 HTML 保存到文件
下面的 Python 代码片段展示了如何使用 SaveOptions 类的 resource_handling_options 属性来管理与文档文件的链接。
1# Save HTML with a linked resources using Python
2
3import os
4import aspose.html as ah
5import aspose.html.saving as sav
6
7# Prepare an output path for the document
8output_dir = "output"
9if not os.path.exists(output_dir):
10 os.makedirs(output_dir)
11
12document_path = os.path.join(output_dir, "save-with-linked-file.html")
13
14# Prepare a simple HTML file with a linked document
15with open(document_path, "w") as file:
16 file.write("<p>Hello, World!</p>" +
17 "<a href='linked.html'>linked file</a>")
18
19# Prepare a simple linked HTML file
20with open(os.path.join(output_dir, "linked.html"), "w") as file:
21 file.write("<p>Hello, linked file!</p>")
22
23# Load the "save-with-linked-file.html" into memory
24document = ah.HTMLDocument(document_path)
25
26# Create a save options instance
27options = sav.HTMLSaveOptions()
28
29# The following line with value '0' cuts off all other linked HTML-files while saving this instance
30# If you remove this line or change value to '1', the 'linked.html' file will be saved as well to the output folder
31options.resource_handling_options.max_handling_depth = 1
32
33# Save the document with the save options
34output_path = os.path.join(output_dir, "save-with-linked-file_out.html")
35document.save(output_path, options)如果需要将 HTML 保存为图像或 PDF 等具有固定布局的文档,可以将文档转换为所需格式。请参阅 HTML 转换器 部分了解更多信息。
将 HTML 保存为 MHTML
在某些情况下,您需要将网页保存为单个文件。MHTML文档可以很方便地实现这一目的,因为它是一个网页归档文件,可以将所有内容都保存在其中。HTMLSaveFormat 枚举 指定了文档的保存格式,可以是 HTML、MHTML 和 Markdown 格式。下面的示例展示了如何使用 save(path, save_format) 方法将 HTML 保存为 MHTML 格式。
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)保存的 “save-to-MTHML.mht “文件存储了 “document.html “和 “linked-file.html “文件的 HTML。
将 HTML 保存为 Markdown
Markdown 是一种使用纯文本语法的标记语言。除了 HTML 转 MHTML 的示例外,您还可以使用 HTMLSaveFormat 保存 HTML 到 Markdown。请看下面的 Python 示例:
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 MHTML format
20document.save(output_path, sav.HTMLSaveFormat.MARKDOWN)保存 SVG
通常,SVG 被嵌入 HTML 文件中,用于表示图像、图标、表格等矢量图形。不过,SVG 也可以从网页中提取出来,像 HTML 文档一样进行独立操作。
由于
SVGDocument 和
HTMLDocument 都遵循
WHATWG DOM 标准,它们的操作(如加载、读取、编辑、转换和保存)在很大程度上是相似的。因此,任何演示操作 HTMLDocument 的示例也可用于 SVGDocument。
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)有关使用 Aspose.SVG Python API 处理和渲染 SVG 文档的更多信息,请参阅 Aspose.SVG for Python via .NET Documentation。
下载 Aspose.HTML for Python via .NET 库,即可成功、快速、轻松地处理 HTML 文档。Python 库可以创建、修改、提取数据、转换和渲染 HTML 文档,而无需外部软件。它支持 EPUB、MHTML、XML、SVG 和 Markdown 等流行文件格式,并可渲染为 PDF、DOCX、XPS 和图像文件格式。
Aspose.HTML 提供免费的在线 HTML 转换器,用于将 HTML 文档转换为各种流行格式。只需从文件或 URL 中加载 HTML,选择要转换的格式,就大功告成了。它速度快,而且完全免费!