用 Java 创建和加载 HTML 文档
HTML 文件
HTMLDocument 类是 Aspose.HTML for Java 库的起点,允许开发人员以编程方式处理 HTML 内容。HTMLDocument 类表示在浏览器中呈现的 HTML 页面,是**文档对象模型(DOM)**的根。
部分 HTMLDocument 功能
- 灵活的构造函数支持从文件、URL、数据流或字符串创建 HTML 文档。
- HTMLDocument 提供了一种内存表示法,可确保在操作时使用完整的 DOM 结构。
- 事件处理包括支持用于异步操作的 DOM 事件。
HTMLDocument 提供了 HTML DOM 的内存表示,它完全基于 W3C DOM 和 WHATWG DOM 规范,许多现代浏览器都支持这些规范。如果您熟悉 WHATWG DOM、 WHATWG HTML和 JavaScript标准,您会发现使用 Aspose.HTML for Java 相当方便。否则,您可以访问 www.w3schools.com,在那里您可以找到许多有关如何处理 HTML 文档的示例和教程。
创建一个空的 HTML 文档
下面的代码片段展示了如何使用默认的 HTMLDocument() 构造函数创建一个空的 HTML 文档并将其保存到文件中。
1// Create an empty HTML document using Java
2
3// Initialize an empty HTML Document
4HTMLDocument document = new HTMLDocument();
5
6// Save the document to disk
7document.save("create-empty-document.html");创建完成后,文件 create-empty-document.html 将显示初始文档结构:空文档包括 <html>``<head> 和 <body> 等元素。有关保存 HTML 文件的更多详情,请参阅
Save HTML Document 一文。
结果文件结构:
1<html>
2 <head></head>
3 <body></body>
4</html>创建新的 HTML 文档
要以编程方式从头开始生成文档,请使用不带参数的 HTMLDocument() 构造函数,如上面的代码片段所示。创建文档对象后,就可以用 HTML 元素填充它。您可以在文档中填充内容,例如创建一个文本节点并将其添加到文档正文中:
1// Create an HTML document using Java
2
3// Initialize an empty HTML document
4HTMLDocument document = new HTMLDocument();
5
6// Create a text node and add it to the document
7Text text = document.createTextNode("Hello, World!");
8document.getBody().appendChild(text);
9
10// Save the document to disk
11document.save("create-new-document.html");从文件加载 HTML
以下代码片段展示了如何从现有文件加载 HTMLDocument :
1// Load HTML from a file using Java
2
3// Prepare the "load-from-file.html" file
4try (java.io.FileWriter fileWriter = new java.io.FileWriter("load-from-file.html")) {
5 fileWriter.write("Hello, World!");
6}
7
8// Load HTML from the file
9HTMLDocument document = new HTMLDocument("load-from-file.html");
10
11// Write the document content to the output stream
12System.out.println(document.getDocumentElement().getOuterHTML());从 URL 加载 HTML
HTMLDocument 类可以从网页中获取并加载 HTML 内容。在下一个代码片段中,您可以看到如何将网页加载到 HTMLDocument 中。
如果您传递了一个错误的 URL,而该 URL 目前无法访问,程序库会抛出带有专用代码 NetworkError 的
DOMException,通知您无法找到所选资源。
1// Load HTML from a URL using Java
2
3// Load a document from https://docs.aspose.com/html/files/document.html web page
4HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html");
5
6System.out.println(document.getDocumentElement().getOuterHTML());从 HTML 代码加载 HTML
如果将 HTML 代码准备为内存中的 Class String 或 Class InputStream 对象,则无需将其保存到文件中,只需将 HTML 代码传入专门的构造函数即可。要从字符串创建文档,请使用带有 HTML 内容和 baseUri 的构造函数 HTMLDocument(content, baseUri):
1// Create HTML from a string using Java
2
3// Prepare HTML code
4String html_code = "<p>Hello, World!</p>";
5
6// Initialize a document from a string variable
7HTMLDocument document = new HTMLDocument(html_code, ".");
8
9// Save the document to disk
10document.save("create-from-string.html");如果您的 HTML 代码中包含链接资源(样式、脚本、图片等),则需要向文档的构造函数传递一个有效的 baseUrl 参数。它将用于在文档加载过程中解析资源的位置。
从数据流中加载 HTML
要从数据流中创建 HTML 文档,可以使用 HTMLDocument(stream, string) 构造函数:
1// Load HTML from a stream using Java
2
3// Create a memory stream object
4String code = "<p>Hello, World! I love HTML!</p>";
5java.io.InputStream inputStream = new java.io.ByteArrayInputStream(code.getBytes());
6
7// Initialize a document from the stream variable
8HTMLDocument document = new HTMLDocument(inputStream, ".");
9
10// Save the document to disk
11document.save("load-from-stream.html");使用 SVG、MHTML 和 EPUB 文档
SVG 文档
由于可缩放矢量图形(SVG)是 W3C 标准的一部分,并且可以嵌入到 HTMLDocument 中,因此我们实现了 SVGDocument 及其所有功能。我们的实现基于官方 SVG2 规范,因此您可以加载、读取、操作官方描述的 SVG 文档。
由于
SVGDocument 和
HTMLDocument 基于相同的
WHATWG DOM 标准,因此这两种文档的所有操作(如加载、读取、编辑、转换和保存)都是相似的。因此,您可以看到的所有使用 HTMLDocument 进行操作的示例也适用于 SVGDocument。
下面的示例展示了如何从内存中的 Class String 变量加载 SVG 文档:
1// Load SVG from a string using Java
2
3// Initialize an SVG document from a string object
4SVGDocument document = new SVGDocument("<svg xmlns='http://www.w3.org/2000/svg'><circle cx='50' cy='50' r='40'/></svg>", ".");
5
6// Write the document content to the output stream
7System.out.println(document.getDocumentElement().getOuterHTML());MHTML 文档
MHTML(聚合 HTML 文档的 MIME 封装)是一种用于创建网页存档的专门格式。Aspose.HTML for Java 库支持 MHTML,但其功能目前仅限于将 MHTML 转换和渲染为其他支持的输出格式。更多信息,请参阅 格式间转换一文。
EPUB 文档
EPUB 是一种广泛用于电子书的电子出版物格式,在 Aspose.HTML for Java 库中与 MHTML 有类似的限制。该库仅支持从 EPUB 到支持的输出格式的渲染操作。更多详情,请访问 格式间转换文章。
异步操作
我们意识到,加载文档可能是一项资源密集型操作,因为它不仅需要加载文档本身,还需要加载所有链接资源和处理所有脚本。在以下代码片段中,我们将演示如何利用异步操作,在不阻塞主线程的情况下加载 HTMLDocument 文档。
以下代码演示了如何通过订阅 “OnReadyStateChange “事件在 Java 中处理 “HTMLDocument”,该事件用于监控文档加载过程。当文档达到 “完成 “状态时,它会使用 getOuterHTML() 方法检索文档根元素的完整 HTML 标记,并将其存储到 StringBuilder 中。 为确保文档有足够的时间加载和事件处理程序的执行,程序会使用 Thread.sleep(5000) 暂停执行 5 秒钟。最后,程序会将捕获的 HTML 打印到控制台。这种方法有助于以编程方式加载、监控和提取网页或文档的完整 HTML 结构,然后对其进行处理、解析或保存,以供日后使用。
1// Load HTML asynchronously using Java
2
3// Create an instance of the HTMLDocument class
4HTMLDocument document = new HTMLDocument();
5
6// Create a string variable for OuterHTML property reading
7StringBuilder outerHTML = new StringBuilder();
8
9// Subscribe to 'ReadyStateChange' event
10// This event will be fired during the document loading process
11document.OnReadyStateChange.add(new DOMEventHandler() {
12 @Override
13 public void invoke(Object sender, Event e) {
14 // Check the value of the 'ReadyState' property
15 // This property is representing the status of the document. For detail information please visit https://www.w3schools.com/jsref/prop_doc_readystate.asp
16 if (document.getReadyState().equals("complete")) {
17 // Fill the outerHTML variable by value of loaded document
18 outerHTML.append(document.getDocumentElement().getOuterHTML());
19 }
20 }
21});
22
23Thread.sleep(5000);
24
25System.out.println("outerHTML = " + outerHTML);与第一个示例不同,下面的示例通过从给定 URL 加载文档并使用 “等待/通知 “而不是固定延迟来演示异步导航。这种方法更可靠,因为它能在文档达到 “完成 “状态时做出精确反应,避免不必要的等待或过早执行。
1// Create an instance of the HTMLDocument class
2
3HTMLDocument document = new HTMLDocument();
4
5// Subscribe to the 'ReadyStateChange' event. This event will be fired during the document loading process
6document.OnReadyStateChange.add(new DOMEventHandler() {
7 @Override
8 public void invoke(Object sender, Event e) {
9 // Check the value of 'ReadyState' property
10 // This property is representing the status of the document. For detail information please visit https://www.w3schools.com/jsref/prop_doc_readystate.asp
11 if (document.getReadyState().equals("complete")) {
12 System.out.println(document.getDocumentElement().getOuterHTML());
13 notifyAll();
14 }
15 }
16});
17
18// Navigate asynchronously at the specified Uri
19document.navigate("https://html.spec.whatwg.org/multipage/introduction.html");
20
21synchronized (this) {
22 wait(10000);
23}此 Java 示例定义了一个自定义的 HTMLDocumentWaiter 类,该类实现了 Runnable,可使用 Aspose.HTML for Java 库异步处理 HTML 文档。构造函数接受一个 HTMLDocumentAsynchronouslyOnLoad 实例,并在一个单独的线程中触发其执行。在 run() 方法中,代码会持续检查是否已收到异步操作的消息,并在两次检查之间以给定的间隔 Thread.sleep(60000) 暂停线程。一旦信息可用或线程被中断,等待者就会停止。通过这种方法,可以与主程序流程并行监控异步加载过程。
1// Create async waiter thread for HTML document loading using Java
2
3public class HTMLDocumentWaiter implements Runnable {
4
5 private final HTMLDocumentAsynchronouslyOnLoad html;
6
7 public HTMLDocumentWaiter(HTMLDocumentAsynchronouslyOnLoad html) throws Exception {
8 this.html = html;
9 this.html.execute();
10 }
11
12 @Override
13 public void run() {
14 System.out.println("Current Thread: " + Thread.currentThread().getName() + "; " + Thread.currentThread().getId());
15
16 while (!Thread.currentThread().isInterrupted() && html.getMsg() == null) {
17 try {
18 Thread.sleep(60000);
19 } catch (InterruptedException e) {
20 throw new RuntimeException(e);
21 }
22 }
23 Thread.currentThread().interrupt();
24 }
25}在本例中,代码使用了 OnLoad 事件,而不是依赖于 ReadyState 检查或手动等待。文档加载完成后,OnLoad 事件就会自动触发,因此这种方法更简单、更高效。事件触发后,程序会检索文档的外部 HTML 并打印到控制台。这种方法避免了不必要的延迟和同步问题,为处理异步加载的 HTML 内容提供了一种更简洁的方法。
1// Handle HTML document onLoad event when navigating to URL using Java
2
3// Create an instance of the HTMLDocument class
4HTMLDocument document = new HTMLDocument();
5
6// Subscribe to the 'OnLoad' event. This event will be fired once the document is fully loaded
7document.OnLoad.add(new DOMEventHandler() {
8 @Override
9 public void invoke(Object sender, Event e) {
10 msg = document.getDocumentElement().getOuterHTML();
11 System.out.println(msg);
12 }
13});
14
15// Navigate asynchronously at the specified Uri
16document.navigate("https://html.spec.whatwg.org/multipage/introduction.html");结论
全面的 DOM 操作:HTMLDocument “类提供了一种强大且符合标准的方法,可按照 W3C 和 WHATWG 规范以编程方式创建、修改和操作 HTML 文档。
灵活的文档创建和加载:使用构造函数,开发人员可以从头开始创建文档,从各种来源(文件、URL、流)加载 HTML,或动态生成内容。
支持高级操作:异步加载和事件处理等功能可实现资源密集型操作的无缝集成,而不会阻塞主应用程序线程。
跨格式兼容性:该库将 HTML 的某些功能扩展到 SVG、MHTML 和 EPUB 等其他文档格式,为处理各种网络内容提供了统一的方法。
您可以从 GitHub 下载完整的示例和数据文件。