C#通过HtmlAgilityPack轻松解析HTML

2023-12-17 10:58

本文主要是介绍C#通过HtmlAgilityPack轻松解析HTML,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

(时间紧张,任务繁重,未完待续……有时间我就回来继续翻译)
这是一篇译文,你没看错,走过路过不要错过,一个英语渣的心塞翻译。

原文在这里Easily Parse HTML Documents in C#


  • C#轻松解析HTML通过HtmlAgilityPack
  • 原文
    • Easily Parse HTML Documents in C#.
      • HtmlAgilityPack
      • Basic Parsing
      • Using XPath


C#轻松解析HTML通过HtmlAgilityPack

你将要创建一个C#应用且需要解析HTML网页。你可能使用正则表达式,但是看起来使用DOM方法更有效率。你是否体会过XPath的优点?

.Net内包含一个HtmlDocument类,


原文

为了防止原文丢失

Easily Parse HTML Documents in C#.

So, you are building a C# application and need to parse a web page’s HTML. You could use regular expressions, but it seems more efficient to use a DOM-based approach. What if you could even take advantage of the power of XPath?

.Net contains an HtmlDocument class, along with HtmlElement, in System.Windows.Forms, which could seem pretty interesting. It does provide basic DOM methods like GetElementById and GetElementsByTagName. However, if you try to create an HtmlDocument object, you will soon notice that it has no public constructor. It is actually a wrapper around an unmanaged class and the only way you can get an instance is through the WebBrowser control. Quite slow and annoying… So, what are the other solutions?

XmlDocument and XmlNode are an interesting solution if you have correctly formatted XML or XHTML. If you are to retrieve content from the web, then you should will need another library that will check the markup and correct it if needed. You may want to try something like Tidy or SGMLReader. Then you can create an XmlDocument and access quite interesting methods to parse and manipulate the nodes.

HtmlAgilityPack

Another solution that I actually now use every time I need to parse HTML is the free and open source HtmlAgilityPack library. It provides HtmlDocument and HtmlNode classes, which are quite similar to .NET’s XmlDocument and XmlNode classes. You can load the HTML either from a file, an URL or a string. There is no need to check the markup validity first as HtmlAgilityPack will take care of making everything valid by closing unclosed tags and fixing other markup errors. Once the document is loaded, you can start having fun parsing through the nodes!

Basic Parsing

The HtmlDocument object provides a getElementById method that let you target a specific node using its Id. You can use properties such as ChildNodes, FirstChild, NextSibling and ParentNode to navigate through the nodes. You can also use the Ancestors and Descendants methods to respectively get a list of all the ancestors or descendants of a node. Optionally, a node name can be given to retrieve only one type of nodes. Use the Attributes property to access a node’s attributes.

Here is a simple example that retrieves a web page and lists all the external links within a given node specified by its Id:

// The HtmlWeb class is a utility class to get the HTML over HTTP
HtmlWeb htmlWeb = new HtmlWeb();// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.somewebsite.com");// Targets a specific node
HtmlNode someNode = document.GetElementbyId("mynode");// If there is no node with that Id, someNode will be null
if (someNode != null)
{// Extracts all links within that nodeIEnumerable<HtmlNode> allLinks = someNode.Descendants("a");// Outputs the href for external linksforeach (HtmlNode link in allLinks){// Checks whether the link contains an HREF attributeif (link.Attributes.Contains("href")){// Simple check: if the href begins with "http://", prints it outif (link.Attributes["href"].Value.StartsWith("http://"))Console.WriteLine(link.Attributes["href"].Value);}}
}

Using XPath

As I mentioned above, HtmlAgilityPack supports XPath. If you don’t know XPath, I really suggest you take some time to learn it. It is quite simple, yet powerful. The HtmlNode class provides two methods to retrieve nodes matching an XPath expression: SelectSingleNode and SelectNodes. The first returns only one node (the first one matching) and the latter returns all matching nodes.

Here is almost the same example as above, but using XPath instead. Load the HtmlDocument object the same way and then:

// Targets a specific node
HtmlNode someNode = document.DocumentNode.SelectSingleNode("//*[@id='mynode']");// If there is no node with that Id, someNode will be null
if (someNode != null)
{// Extracts all links within that node// Note the leading dot (.) to make it look relative to the current node instead of the whole documentHtmlNodeCollection allLinks = someNode.SelectNodes(".//a");

The remaining is the same.

But that code is not any shorter or simpler than the previous one! It might even actually seem more complicated with that XPath syntax. That’s right, but here comes the power of XPath. Both expressions could be combined into only one that would do everything at once. And here is the new code after the HtmlDocument object loading as above:

// Extracts all links under a specific node that have an href that begins with "http://"
HtmlNodeCollection allLinks = document.DocumentNode.SelectNodes("//*[@id='mynode']//a[starts-with(@href,'http://')]");// Outputs the href for external links
foreach (HtmlNode link in allLinks)Console.WriteLine(link.Attributes["href"].Value);

Simple enough? Only the XPath part might be a bit hard to understand if you are new to it, but you will get used and eventually read it easily. This example is quite simple, but there is a lot more you can do using XPath to parse through nodes.

I hope this short introduction to HtmlAgilityPack will help you getting started using this really nice library and help you with your projects!

这篇关于C#通过HtmlAgilityPack轻松解析HTML的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/504124

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程