用 Python 浏览 HTML

HTML 导航

Aspose.Html.Dom 命名空间提供了表示任何 HTML、XML 或 SVG 文档并与之交互的 API,它完全基于许多现代浏览器支持的 WHATWG DOM 规范。

本文介绍了如何使用 Aspose.HTML for Python 通过 .NET 以编程方式从 HTML 文档中提取数据。您会发现

  • 如何使用 Python API 浏览 HTML 文档并详细检查其中的元素;
  • 如何使用 CSS 选择器和 XPath 查询浏览文档。

浏览 HTML 涉及访问和操作文档中的元素及其关系。 Aspose.HTML for Python via .NET允许您导航和检查 HTML,这涉及使用库提供的文档对象模型(DOM)。下面的列表显示了访问所有 DOM 元素的最简单方法:

  1. 文档对象模型(DOM) .DOM 结构以节点树的形式表示 HTML 文档。每个节点代表文档的一部分,如元素、文本或注释。
  1. 获取要素
  1. 浏览 DOM 树
  1. 操纵元素

API Reference Source 全面列出了 aspose.html.dom 命名空间中的类和方法。

浏览 DOM 树

我们将讨论 DOM 如何在内存中表示 HTML 文档,以及如何使用 API 浏览 HTML 文件。 Node 类的四个属性–first_childlast_childnext_siblingnext_sibling–都提供了对与当前元素有定义关系的另一个元素的实时引用,如果相关元素存在的话。

使用上述属性,您可以浏览 HTML 文档,如下所示:

 1# Navigate the HTML DOM using Python
 2
 3import aspose.html as ah
 4
 5# Prepare HTML code
 6html_code = "<span>Hello</span> <span>World!</span>"
 7
 8# Initialize a document from the prepared code
 9with ah.HTMLDocument(html_code, ".") as document:
10    # Get the reference to the first child (first SPAN) of the BODY
11    element = document.body.first_child
12    print(element.text_content)  # output: Hello,
13
14    # Get the reference to the whitespace between html elements
15    element = element.next_sibling
16    print(element.text_content)  # output: " "
17
18    # Get the reference to the second SPAN element
19    element = element.next_sibling
20    print(element.text_content)  # output: World!

检查 HTML

Aspose.HTML 包含一系列基于 元素遍历规范的方法。您可以使用该 API 对文档及其元素进行详细检查。下面的 Python 代码演示了如何使用 Aspose.HTML for Python 通过 .NET 浏览和提取 HTML 文档中的特定元素及其属性。

 1# Navigate and inspect HTML document using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Load a document from a file
 7data_dir = "data"  # Change this to your actual data directory
 8document_path = os.path.join(data_dir, "html_file.html")
 9with ah.HTMLDocument(document_path) as document:
10    # Get the html element of the document
11    element = document.document_element
12    print(element.tag_name)  # HTML
13
14    # Get the last element of the html element
15    element = element.last_element_child
16    print(element.tag_name)  # BODY
17
18    # Get the first element of the body element
19    element = element.first_element_child
20    print(element.tag_name)  # H1
21    print(element.text_content)  # Header 1

所提供的 Python 代码首先定义了位于 data 目录下的 HTML 文件的路径。

XPath 查询

XPath 查询( XML 路径语言)是HTML 导航的替代方法,通常简称为 XPath。它是一种查询语言,可用来查询 HTML 文档中的数据。它基于 HTML 文档的 DOM 表示法,并根据各种标准选择节点。XPath 表达式的语法非常简单,更重要的是,它易于阅读和支持。

下面的示例展示了如何在 Aspose.HTML Python API 中使用 XPath 查询:

 1# How to use XPath to select nodes using Python
 2
 3import aspose.html as ah
 4import aspose.html.dom.xpath as hxpath
 5
 6# Prepare HTML code
 7code = """
 8    <div class='happy'>
 9        <div>
10            <span>Hello,</span>
11        </div>
12    </div>
13    <p class='happy'>
14        <span>World!</span>
15    </p>
16"""
17
18# Initialize a document based on the prepared code
19with ah.HTMLDocument(code, ".") as document:
20    # Here we evaluate the XPath expression where we select all child SPAN elements from elements whose 'class' attribute equals to 'happy'
21    result = document.evaluate("//*[@class='happy']//span",
22                               document,
23                               None,
24                               hxpath.XPathResultType.ANY,
25                               None)
26
27    # Iterate over the resulted nodes
28    node = result.iterate_next()
29    while node is not None:
30        print(node.text_content)
31        node = result.iterate_next()
32        # output: Hello,
33        # output: World!

Aspose.HTML Python 库中的 evaluate() 方法允许您针对 HTML 或 XML 文档执行 XPath 查询,从而实现详细的数据提取和导航。该方法将 XPath 表达式作为主参数,指定要执行的查询,并根据定义的结果类型返回一个 XPathResult 对象。

CSS 选择器

除了 HTML 导航和 XPath 之外,Aspose.HTML Python API 还支持 CSS 选择器 API。该 API 允许您使用 CSS 选择器 语法制定搜索模式,以识别和选择 HTML 文档中的元素。例如, query_selector_all(selector) 方法可用于遍历 HTML 文档并检索与指定 CSS 选择器匹配的元素。该方法接受 CSS 选择器字符串作为参数,并返回一个包含符合选择器条件的所有元素的 NodeList 方法。使用 CSS 选择器,您可以根据元素的属性、类、ID 和其他标准有效地查找和处理元素,使其成为一种通用工具,既可用于简单的文档解析任务,也可用于复杂的文档解析任务。这一功能对于 HTML 文档中的样式设计、数据提取和内容处理等任务尤为有用。

 1# Extract nodes Using CSS selector using Python
 2
 3import aspose.html as ah
 4
 5# Prepare HTML code
 6code = """
 7    <div class='happy'>
 8        <div>
 9            <span>Hello,</span>
10        </div>
11    </div>
12    <p class='happy'>
13        <span>World!</span>
14        <p>I use CSS Selector.</p>
15    </p>
16"""
17
18# Initialize a document based on the prepared code
19with ah.HTMLDocument(code, ".") as document:
20    # Create a CSS Selector that extracts all elements whose "class" attribute equals "happy" and their child <span> elements
21    elements = document.query_selector_all(".happy span")
22
23# Iterate over the resulted list of elements
24    for element in elements:
25        print(element.text_content)
26        # output: Hello,
27        # output: World!

结论

Aspose.HTML for Python via .NET 库为处理 HTML、XML 和 SVG 文档提供了一套强大的工具,符合现代浏览器广泛支持的 WHATWG DOM 规范。使用 “HTMLDocument “类及其各种导航属性和方法,您可以有效地与 HTML 内容交互并对其进行操作,从而避免手动提取数据的复杂性,并专注于项目中更具战略性的方面。

Aspose.HTML 提供免费的在线 HTML 网络应用程序,是转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具、网络可访问性检查等的在线集合。这些应用程序可在任何带有网络浏览器的操作系统上运行,无需安装任何其他软件。使用我们的 HTML 网络应用程序集来处理您的日常事务,让您的工作流程更加顺畅!

文本 “HTML 网络应用程序”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.