C# 中的 HTML 导航
使用 Aspose.HTML for .NET库,您可以轻松创建自己的应用程序,因为我们的应用程序接口提供了一个强大的工具集,用于分析和收集 HTML 文档中的信息。
本文介绍了如何使用 Aspose.HTML for .NET API 以编程方式从 HTML 文档中提取数据。您将了解到
- 如何使用 API 浏览 HTML 文档并对其元素进行详细检查;
- 关于使用自定义过滤器迭代文档元素;
- 如何使用 CSS 选择器或 XPath 查询浏览文档。
HTML 导航
Aspose.Html.Dom 命名空间提供了表示 HTML、XML 或 SVG 文档并与之交互的 API,它完全基于许多现代浏览器支持的 WHATWG DOM 规范。DOM 是在浏览器中加载的文档模型,以节点树的形式表示文档,其中每个节点都代表文档的一部分(如元素、文本字符串或注释)。
我们将讨论 DOM 如何在内存中表示 HTML 文档,以及如何使用 API 在 HTML 文件中进行导航。有许多方法可用于 HTML 导航。下面列出了访问所有 DOM 元素的最简单方法:
Property | Description |
---|---|
FirstChild | Accessing this property of an element must return a reference to the first child node. |
LastChild | Accessing this property of an element must return a reference to the last child node |
NextSibling | Accessing this property of an element must return a reference to the sibling node of that element which most immediately follows that element. |
PreviousSibling | Accessing this property of an element must return a reference to the sibling node of that element which most immediately precedes that element. |
ChildNodes | Returns a list that contains all children of that element. |
Node类属性中有四个属性–FirstChild、LastChild、NextSibling 和 PreviousSibling,每个属性都提供了对另一个元素的实时引用,如果相关元素与当前元素存在定义的关系的话。有关 Aspose.Html.Dom 命名空间中代表的类和方法的完整列表,请访问 API Reference Source。
使用上述属性,您可以浏览 HTML 文档,如下所示:
1// Navigate the HTML DOM using C#
2
3// Prepare HTML code
4string html_code = "<span>Hello,</span> <span>World!</span>";
5
6// Initialize a document from the prepared code
7using (HTMLDocument document = new HTMLDocument(html_code, "."))
8{
9 // Get the reference to the first child (first <span>) of the <body>
10 Node element = document.Body.FirstChild;
11 Console.WriteLine(element.TextContent); // output: Hello,
12
13 // Get the reference to the whitespace between html elements
14 element = element.NextSibling;
15 Console.WriteLine(element.TextContent); // output: ' '
16
17 // Get the reference to the second <span> element
18 element = element.NextSibling;
19 Console.WriteLine(element.TextContent); // output: World!
20
21 // Set an html variable for the document
22 string html = document.DocumentElement.OuterHTML;
23
24 Console.WriteLine(html); // output: <html><head></head><body><span>Hello,</span> <span>World!</span></body></html>
25}
检查 HTML
Aspose.HTML 包含一系列基于 元素遍历规范的方法。您可以使用该 API 对文档及其元素进行详细检查。以下代码示例展示了元素遍历功能的一般用法。
1// Access and navigate HTML elements in a document using C#
2
3// Load a document from a file
4string documentPath = Path.Combine(DataDir, "html_file.html");
5
6using (HTMLDocument document = new HTMLDocument(documentPath))
7{
8 // Get the html element of the document
9 Element element = document.DocumentElement;
10 Console.WriteLine(element.TagName); // HTML
11
12 // Get the last element of the html element
13 element = element.LastElementChild;
14 Console.WriteLine(element.TagName); // BODY
15
16 // Get the first element in the body element
17 element = element.FirstElementChild;
18 Console.WriteLine(element.TagName); // H1
19 Console.WriteLine(element.TextContent); // Header 1
20}
注意: 您需要指定 HTML 源文件在本地文件系统中的路径(“documentPath”)。
通过 Document 类的
DocumentElement 属性,可以直接访问文档中的 <html>
元素(
html_file.html)。Document 类的 LastElementChild 属性返回 <html>
元素的最后一个子元素。它就是 <body>
元素。根据上面的代码片段,变量 element
再次被重载,FirstElementChild 属性返回 <body>
元素的第一个子元素。它就是 <h1>
元素。
自定义过滤器的使用
对于更复杂的情况,如果需要根据特定模式查找节点(例如,获取标题、链接等列表),可以使用专门的 TreeWalker 或 NodeIterator 对象,并自定义 Filter 实现。
下面的示例展示了如何实现自己的 NodeFilter,以跳过除图像之外的所有元素:
1// Filter only <img> elements in HTML tree using C#
2
3class OnlyImageFilter : Aspose.Html.Dom.Traversal.Filters.NodeFilter
4{
5 public override short AcceptNode(Node n)
6 {
7 // The current filter skips all elements, except IMG elements
8 return string.Equals("img", n.LocalName)
9 ? FILTER_ACCEPT
10 : FILTER_SKIP;
11 }
12}
使用过滤器后,就可以按如下方式使用 HTML 导航:
1// Implement NodeFilter to skip all elements except images
2
3// Prepare HTML code
4string code = @"
5 <p>Hello,</p>
6 <img src='image1.png'>
7 <img src='image2.png'>
8 <p>World!</p>";
9
10// Initialize a document based on the prepared code
11using (HTMLDocument document = new HTMLDocument(code, "."))
12{
13 // To start HTML navigation, we need to create an instance of TreeWalker
14 // The specified parameters mean that it starts walking from the root of the document, iterating all nodes and using our custom implementation of the filter
15 using (ITreeWalker iterator = document.CreateTreeWalker(document, NodeFilter.SHOW_ALL, new OnlyImageFilter()))
16 {
17 while (iterator.NextNode() != null)
18 {
19 // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
20 // So, we don't need the additional validations here
21 HTMLImageElement image = (HTMLImageElement)iterator.CurrentNode;
22
23 Console.WriteLine(image.Src);
24 // output: image1.png
25 // output: image2.png
26
27 // Set an html variable for the document
28 string html = document.DocumentElement.OuterHTML;
29 }
30 }
31}
XPath 查询
XPath 查询( XML 路径语言)是HTML 导航的替代方法,通常简称为 XPath。它是一种查询语言,可用来查询 HTML 文档中的数据。它基于 HTML 文档的 DOM 表示法,并根据各种标准选择节点。XPath 表达式的语法非常简单,更重要的是,它易于阅读和支持。
下面的示例展示了如何在 Aspose.HTML API 中使用 XPath 查询:
1// How to use XPath to select nodes using C#
2
3// Prepare HTML code
4string code = @"
5 <div class='happy'>
6 <div>
7 <span>Hello,</span>
8 </div>
9 </div>
10 <p class='happy'>
11 <span>World!</span>
12 </p>
13";
14
15// Initialize a document based on the prepared code
16using (HTMLDocument document = new HTMLDocument(code, "."))
17{
18 // Here we evaluate the XPath expression where we select all child <span> elements from elements whose 'class' attribute equals to 'happy':
19 IXPathResult result = document.Evaluate("//*[@class='happy']//span",
20 document,
21 null,
22 XPathResultType.Any,
23 null);
24
25 // Iterate over the resulted nodes
26 for (Node node; (node = result.IterateNext()) != null;)
27 {
28 Console.WriteLine(node.TextContent);
29 // output: Hello,
30 // output: World!
31 }
32}
文章 如何在 HTML 中使用 XPath 查询 – Evaluate() 方法 介绍了如何使用 Evaluate() 方法浏览 HTML 文档并根据各种条件选择节点。通过 C# 示例,您将了解如何使用 XPath 查询选择具有指定名称的所有节点。
CSS 选择器
除了 HTML Navigation 和 XPath,您还可以使用我们的库同样支持的 CSS Selector API。该 API 可根据 CSS 选择器 语法创建搜索模式,以匹配文档树中的元素。
在下面的示例中,我们使用 QuerySelectorAll() 方法浏览 HTML 文档并搜索所需的元素。该方法将查询选择器作为参数,并返回一个包含所有符合指定选择器的元素的 NodeList。
1// Extract nodes Using CSS selector in C#
2
3// Prepare HTML code
4string code = @"
5 <div class='happy'>
6 <div>
7 <span>Hello,</span>
8 </div>
9 </div>
10 <p class='happy'>
11 <span>World!</span>
12 </p>
13";
14
15// Initialize a document based on the prepared code
16using (HTMLDocument document = new HTMLDocument(code, "."))
17{
18 // Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'happy' and their child <span> elements
19 NodeList elements = document.QuerySelectorAll(".happy span");
20
21 // Iterate over the resulted list of elements
22 foreach (HTMLElement element in elements)
23 {
24 Console.WriteLine(element.InnerHTML);
25 // output: Hello,
26 // output: World!
27 }
28}
另见
有关如何有效应用选择器来选择要样式化的元素的更多信息,请访问文章 CSS 选择器。您将学习基本选择器、组合选择器、属性选择器、组选择器和伪选择器。
在 如何使用 CSS 选择器 – QuerySelector() 和 QuerySelectorAll() 这篇文章中,你将学习如何有效地应用选择器来选择想要样式的元素。QuerySelector() 和 QuerySelectorAll() 是用于查询与 CSS 选择器匹配的 DOM 元素的方法。
您可以从 GitHub 下载完整的 C# 示例和数据文件。
Aspose.HTML 提供免费的在线 HTML 网络应用程序,是转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具等的在线集合。这些应用程序可在任何装有网络浏览器的操作系统上运行,无需安装任何其他软件。无论你身在何处,都能轻松转换、合并、编码、生成 HTML 代码,从网络中提取数据,或从搜索引擎优化的角度分析网页。使用我们的 HTML 网络应用程序集来处理您的日常事务,让您的工作流程天衣无缝!