How to get css properties from a parsed html element using AngleSharp

2.9k views Asked by At

Having this CSS:

.foo { background-size: 10px 20px; }

And this Html:

<span class="foo"></span>

And this C#:

var parser = new HtmlParser();
var doc = parser.Parse("http://localhost/test.html");
var element = doc.QuerySelector("span.foo");

How do I get the associated background width and height to element?

(Currently I'm using AngleSharp version 0.9.9)

1

There are 1 answers

2
Florian Rappl On BEST ANSWER

First of all the C# code is wrong. The string you pass on to parser.Parse is an HTML code, not an URI. Also your code does not do any CSS parsing - it is only using an HTML parser. Thus let's use a browsing context to get all you need.

var config = Configuration.Default.WithDefaultLoader().WithCss();
var context = BrowsingContext.New(config);
var document = context.OpenAsync("http://localhost/test.html").Result;
var element = document.QuerySelector("span.foo");
var style = document.DefaultView.GetComputedStyle(element);
var size = style.BackgroundSize;

Keep in mind that element may be null if no such element exists (none matching the query) and that the GetComputedStyle method only works in a limited way. Also if your CSS is defined in an external style sheet make sure to activate resource loading.

Hope this helps!