AngleSharp

AngleSharp是一个.NET库,提供与现代浏览器相同的HTML 5解析器和DOM API。通过NuGet安装后,可以方便地解析和操作HTML文档。它支持简单的文档操作、JavaScript评估、DOM事件和复杂的DOM交互。AngleSharp的DOM模型遵循W3C标准,同时提供超越标准的额外功能。

所需

AngleSharp目前有两种版本:Windows for.NET 4.6和普通的.NET标准2.0平台。
库的大多数特性都不需要.NET 4.6,这意味着您可以创建自己的分叉并修改它以使用以前版本的.NET-Framework。

通过NuGet获取AngleSharp。

将AngleSharp集成到项目中的最简单方法是使用NuGet。您可以通过打开包管理器控制台(PM)并输入以下语句来安装AngleSharp:

Install-Package AngleSharp

您还可以使用图形库包管理器(“管理用于解决方案的NuGet包”)。在官方的NuGet在线提要中搜索“AngleSharp”将找到这个库。

第一步

在最简单的情况下,您已经有了一个文档源,并希望对其进行解析。这可能如下所示:

using System;
using AngleSharp;
using AngleSharp.Html.Parser;

class MyClass {
   
   
    static async void Main() {
   
   
        //Use the default configuration for AngleSharp
        var config = Configuration.Default;

        //Create a new context for evaluating webpages with the given config
        var context = BrowsingContext.New(config);

        //Source to be parsed
        var source = "<h1>Some example source</h1><p>This is a paragraph element";

        //Create a virtual request to specify the document to load (here from our fixed string)
        var document = await context.OpenAsync(req => req.Content(source));

        //Do something with document like the following
        Console.WriteLine("Serializing the (original) document:");
        Console.WriteLine(document.DocumentElement.OuterHtml);

        var p = document.CreateElement("p");
        p.TextContent = "This is another paragraph.";

        Console.WriteLine("Inserting another element in the body ...");
        document.Body.AppendChild(p);

        Console.WriteLine("Serializing the document again:");
        Console.WriteLine(document.DocumentElement.OuterHtml);
    }
}

当然,还可以进一步执行更多DOM操作。

IBrowsingContext表示进行文档评估的浏览上下文。这是解析任何HTML页面所必需的构造。它还允许提交表格,以下链接,下载资源,等等。我们可以把它想象成标准浏览器中的一个选项卡。

或者,我们可以在开始时使用以下代码:

var context = BrowsingContext.New(config);
var parser = context.GetService<IHtmlParser>();
var source = "<h1>Some example source</h1><p>This is a paragraph element";
var document = parser.ParseDocument(source);

那么什么是IHtmlParser?这是一个表示HTML 5解析器前端的类。它具有创建以下实例的方法:IHtmlDocument,其中包含解析的DOM。由于HTML对于可能出现的错误非常宽松,所以没有什么比异常更好的了。我们可能只会收到一些错误信息。这些消息可以通过一个特殊的接口接收,并且应该被视为警告。

DOM

AngleSharp背后的想法是提供最先进的解析器(用于css、HTML和相关对象,如URL),这些解析器生成与现代浏览器相同的DOM。相同的DOM意味着在JavaScript/当前浏览器中使用相同的API。这个API是标准化的,并且在web开发人员中是众所周知的.此外,DOM交互的生动活泼不仅限于JavaScript或浏览器托管场景。AngleSharp将使将现代浏览器的核心引入您的代码成为可能。

整个DOM已被传输到逻辑类结构中。如下图所示,可以解析此结构的一部分。请注意,图中显示了一个较旧的DOM模型。当前版本的AngleSharp实现了最新的DOM模型,这略有不同。尽管如此,这幅画仍然是有用的,以获得正确的想法。

The DOM as class relations

DOM有一些限制:

一般情况下,不能仅仅创建元素-几乎总是有工厂在IDocument实例或专门化,例如IHtmlDocument
已知元素的继承是不可能的。
DOM的修改必须遵循给定的路径
这意味着不能编写类似的代码(注意:HtmlParagraphElement元素是内部的-它是IHtmlParagraphElement接口),

var paragraph = new HTMLParagraphElement();

因为这在JavaScript中也是不可能的。需要的是IDocument接口。如果我们假设这个实例被调用document我们现在可以写

var paragraph = document.CreateElement("p");

它创建段落 (<p> )元素,并将给定的文档指定为节点的所有者。与JavaScript/DOM世界一样,我们没有在文档中的任何地方追加该段。当一个元素没有被追加时,它没有父元素,因此不会出现在DOM树中。因此,它将不再序列化,某些特殊操作将毫无意义。此外,DOM树上的查询不会显示给定的元素。

另一方面,这些限制导致将所有构造函数标记为internal…这会防止继承(即使类可能不是sealed),并要求用户遵循给定的路径。

JavaScript等脚本语言的优点是即使CreateElement只返回IElement,您甚至可以访问以下方面的专门属性和方法:IHtmlElement,如果有的话。在静态类型化语言(如C#)中,我们需要强制转换。一种解决办法是使用dynamic,或者方便的扩展方法,如

var paragraph = document.CreateElement<IHtmlParagraphElement>();

此操作并直接返回类型的对象。IHtmlParagraphElement…不需要强制转换,保存了一个(可疑的)字符串分配。这个特定的扩展方法被放置在命名空间中。AngleSharp.Dom.

超越DOM

AngleSharp提供了一些无法通过标准DOM属性和方法访问的属性和方法。要区分标准化和扩展的简单属性类,称为DomNameAttribute已经被添加了。该属性应用于那些在正式W3C标准中也指定了修饰类/事件/方法或属性的情况下。此外,还设置了官方名称,因为AngleSharp遵循PascalCase约定,而DOM遵循CamelCase约定。

<
### AngleSharp C# HTML Parsing Library Documentation and Usage Examples #### Overview of AngleSharp AngleSharp is a powerful web parsing library designed specifically for .NET applications. This library allows developers to parse and manipulate HTML documents effectively using modern standards such as CSS Selectors, DOM Level 2 Events, and more[^1]. #### Installation Requirements To use AngleSharp within projects, one must ensure that development environments meet specific criteria. Since AngleSharp utilizes features introduced in C# 7.1, it necessitates the employment of compilers compatible with this version or later versions of C#. For optimal performance during project creation and management on Windows systems, utilizing Integrated Development Environments (IDEs) like Visual Studio 2017+ is highly advised due to their comprehensive support for newer language constructs found in recent iterations of C#[^1]. For cross-platform compatibility outside traditional Microsoft ecosystems, alternative editors supporting advanced coding functionalities through extensions become essential tools. Editors such as VSCode paired alongside plugins implementing Language Server Protocol provide robust solutions across various operating systems without sacrificing functionality provided natively under Windows configurations. #### Basic Example Code Demonstrating Document Loading from String Input Source Below demonstrates how simple loading an HTML string into memory can be accomplished via AngleSharp: ```csharp using System; using System.Threading.Tasks; using AngleSharp; class Program { static async Task Main(string[] args){ var config = Configuration.Default.WithDefaultLoader(); var context = BrowsingContext.New(config); const string htmlContent = "<!DOCTYPE html><html lang='en'><head><title>Test Page</title></head><body><p>Hello world!</p></body></html>"; var document = await context.OpenAsync(req => req.Content(htmlContent)); Console.WriteLine(document.Title); // Outputs "Test Page" } } ``` This example initializes necessary components required by AngleSharp before creating instances capable of interpreting raw textual representations conforming to HyperText Markup Language specifications. #### Advanced Features Utilizing CSS Selectors for Element Extraction Beyond basic operations involving entire pages' contents, finer control over individual elements becomes possible thanks to built-in selector engines integrated directly inside AngleSharp's core architecture. Leveraging these capabilities enables precise targeting based upon attributes present throughout structured hierarchies defined within source materials being processed programmatically. ```csharp var paragraphs = document.QuerySelectorAll("p"); foreach(var paragraphElement in paragraphs){ Console.WriteLine(paragraphElement.TextContent); } ``` In this snippet above, all `<p>` tags contained anywhere beneath root nodes will get selected iteratively allowing access to inner text values associated individually per iteration cycle executed sequentially against matched results returned after query execution completes successfully.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值