简体   繁体   English

使用 AngleSharp 解析 CSS

[英]Parsing CSS with AngleSharp

I'm trying to parse an HTML web page and its CSS with AngleSharp.我正在尝试使用 AngleSharp 解析 HTML 网页及其 CSS。 Sadly I only found depreciated examples for this, and I am struggling to find an up to date implementation.可悲的是,我只找到了折旧的例子,我正在努力寻找最新的实现。

Currently, I am trying this:目前,我正在尝试这个:

  var config = Configuration.Default.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true });
  var context = BrowsingContext.New(config);
  var address = "www.foo.com"
  var document = await context.OpenAsync(address);
  var styleSheets = document.styleSheets;

When I try to access the styleSheets it always returns an empty list.当我尝试访问 styleSheets 时,它总是返回一个空列表。 What is the correct way to parse CSS with AngleSharp?使用 AngleSharp 解析 CSS 的正确方法是什么? Maybe one could include an example in the docs.也许可以在文档中包含一个示例。

Regards问候

Thanks for asking this question and sorry for some outdated documentation that is still flying around.感谢您提出这个问题,并对一些仍在飞来飞去的过时文档感到抱歉。

AngleSharp does not come with CSS; AngleSharp 不附带 CSS; instead, AngleSharp can be extended with functionality from other libraries.相反,可以使用其他库的功能扩展 AngleSharp。 One of these libraries is AngleSharp.Css .这些库之一是AngleSharp.Css

As the name suggests this library brings CSS capabilities.顾名思义,这个库带来了 CSS 功能。

Assuming you installed both (AngleSharp and AngleSharp.Css) via NuGet you can do:假设您通过 NuGet 安装了(AngleSharp 和 AngleSharp.Css),您可以执行以下操作:

  var config = Configuration.Default.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }).WithCss();
  var context = BrowsingContext.New(config);
  var address = "http://www.example.com"; // any reason for dropping the protocol?
  var document = await context.OpenAsync(address);
  var sheet = document.QuerySelector<IHtmlLinkElement>("link[rel=stylesheet]")?.Sheet;

I used the following namespace imports.我使用了以下命名空间导入。

    AngleSharp
    AngleSharp.Dom
    AngleSharp.Html.Dom
    AngleSharp.Io

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM