Parsing CSS with AngleSharp

Issue

I’m trying to parse an HTML web page and its CSS with AngleSharp. 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. What is the correct way to parse CSS with AngleSharp? Maybe one could include an example in the docs.

Regards

Solution

Thanks for asking this question and sorry for some outdated documentation that is still flying around.

AngleSharp does not come with CSS; instead, AngleSharp can be extended with functionality from other libraries. One of these libraries is AngleSharp.Css.

As the name suggests this library brings CSS capabilities.

Assuming you installed both (AngleSharp and AngleSharp.Css) via NuGet you can do:

  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!

Answered By – Florian Rappl

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published