{"id":123012,"date":"2020-11-30T13:00:56","date_gmt":"2020-11-30T10:00:56","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it\/"},"modified":"2020-11-30T13:00:56","modified_gmt":"2020-11-30T10:00:56","slug":"using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it\/","title":{"rendered":"#Using AngleSharp in PowerShell 7 to Parse Webpages \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_91 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6b12ca8331834\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6b12ca8331834\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it\/#Installing_and_Loading_AngleSharp\" >Installing and Loading AngleSharp<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it\/#Parsing_a_Webpage\" >Parsing a Webpage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/using-anglesharp-in-powershell-7-to-parse-webpages-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Using AngleSharp in PowerShell 7 to Parse Webpages \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4374\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/8fec593cd19e3b20a0773cafaaaaf848\/p\/uploads\/2020\/03\/23e4a5a4.png\" alt=\"Powershell logo\" width=\"1400\" height=\"578\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p><a rel=\"nofollow noopener noreferrer\" target=\"_blank\" href=\"https:\/\/anglesharp.github.io\/\">AngleSharp<\/a> is a .NET library that makes parsing and working with HTML content quick and easy. As AngleSharp is written in .NET, you can use and consume the output in PowerShell as well. Combining these two allows you to quickly and easily <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">script<\/a> HTML content. In this article, we will explore how to set up AngleSharp and consume a weather page, and convert the data into a PowerShell object.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Installing_and_Loading_AngleSharp\"><\/span>Installing and Loading AngleSharp<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Installing AngleSharp is easy using the <code>Install-Package<\/code> command. You can even install the package into the <code>CurrentUser<\/code> scope which means you do not need administrative rights to use this library. The package is contained in the <code>NuGet<\/code> library.<\/p>\n<pre><code class=\"language-powershell\">Install-Package 'AngleSharp' -Scope 'CurrentUser' -Source 'Nuget'&#13;\n<\/code><\/pre>\n<p>Next we will want to load AngleSharp for use in our PowerShell script. To do this we will want to use the <code>Add-Type<\/code> cmdlet to directly load the DLL for the library. Below is code that assists in locating the latest .NET version and loading that path, if the library isn\u2019t already loaded in your session.<\/p>\n<pre><code class=\"language-powershell\">If ( -Not ([System.Management.Automation.PSTypeName]'AngleSharp.Parser.Html.HtmlParser').Type ) {&#13;\n    $standardAssemblyFullPath = (Get-ChildItem -Filter '*.dll' -Recurse (Split-Path (Get-Package -Name 'AngleSharp').Source)).FullName | Where-Object {$_ -Like \"*standard*\"} | Select-Object -Last 1&#13;\n&#13;\n    Add-Type -Path $standardAssemblyFullPath -ErrorAction 'SilentlyContinue'&#13;\n} # Terminate If - Not Loaded&#13;\n<\/code><\/pre>\n<p>Read on to discover how to parse the webpage content and create a useful PowerShell object!<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Parsing_a_Webpage\"><\/span>Parsing a Webpage<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Of course, the whole point of this is to actually parse a web page. In this example we will load the content from <code>Invoke-WebRequest<\/code> and then using the result, parse the content in AngleSharp. We are going to use a local 7-day forecast from the National Weather Service to pull in weather data and convert to an object. First, let\u2019s retrieve the weather data.<\/p>\n<pre><code class=\"language-powershell\">$Request = Invoke-WebRequest -Uri \"&lt;https:\/\/forecast.weather.gov\/MapClick.php?lat=40.48675500000007&amp;lon=-88.99177999999995&gt;\"&#13;\n<\/code><\/pre>\n<p>The data for the site that we are interested in is in the <code>Content<\/code> property, but it is the full HTML source, which is a lot to process. Often, it is easiest to use Chrome Developer Tools to locate the section of the HTML source that we want to use (F12 in Chrome for the site you want to inspect).<\/p>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-8250 aligncenter\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/4e0486256835e80edd822102f64d0dbd\/p\/uploads\/2020\/11\/65f278a6.png\" alt=\"\" width=\"1326\" height=\"795\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The HTML structure of the NWS weather page.<\/p>\n<p>Thankfully, there is a <code>div<\/code> container with an unordered list that we can parse. The next step is to actually load the retrieved content into AngleSharp.<\/p>\n<pre><code class=\"language-powershell\">$Parser = New-Object AngleSharp.Html.Parser.HtmlParser&#13;\n$Parsed = $Parser.ParseDocument($Request.Content)&#13;\n<\/code><\/pre>\n<p>Now that we have the parsed content available in our <code>$Parsed<\/code> variable, we can start to manipulate this data to get to just the section we want. Very conveniently, the NWS site provides an ID just for this unordered list named <code>seven-day-forecast-list<\/code>. Since each ID is unique on an HTML page, this makes the list easy to target. Using the <code>All<\/code> property on our parsed content, we can retrieve just the object with the ID of <code>seven-day-forecast-list<\/code>.<\/p>\n<pre><code class=\"language-powershell\">$ForecastList = $Parsed.All | Where-Object ID -EQ 'seven-day-forecast-list'&#13;\n<\/code><\/pre>\n<p>This will result in a lot of different properties, but we are focused on the <code>ChildNodes<\/code> property as it will contain each <code>li<\/code> containing the data we need. To get an idea of what we are looking to target in our object, let\u2019s take a look at an individual <code>li<\/code>. There are a handful of elements with classes that we can target.<\/p>\n<ul>\n<li><code>period-name<\/code> \u2013 The relative time period.<\/li>\n<li><code>short-desc<\/code> \u2013 A condensed description of the weather.<\/li>\n<li><code>temp temp-high<\/code> \u2013 The high temperature.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-8251 aligncenter\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/86789756468d0f09f83002b0506f66a2\/p\/uploads\/2020\/11\/7f858d3f.png\" alt=\"\" width=\"996\" height=\"354\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>HTML structure of a single tombstone-container element.<\/p>\n<p>You may notice that the <code>img<\/code> tag contains an <code>alt<\/code> property with a lot of useful information. It\u2019s pretty easy to find the class to target as it is stored in the <code>classname<\/code> property of the child node. To target the <code>alt<\/code> element we will have to rely on a slightly different method, <code>QuerySelectorAll<\/code> which uses traditional CSS selectors to make complex targeting easy.<\/p>\n<pre><code class=\"language-powershell\">$ForecastList.ChildNodes | ForEach-Object {&#13;\n    # Retrieve just the content of the tombstone-container div underneath the forecast-tombstone li element.&#13;\n  $Node = $_.ChildNodes | Where-Object ClassName -EQ 'tombstone-container'&#13;\n&#13;\n  [PSCustomObject]@{&#13;\n        # Search the child nodes under the tombstone-container and find the element named period-name. Retrieve just the innerHTML which is the text value. This includes a break element, &lt;br&gt; of which we don't need, so replace that with a space instead.&#13;\n    \"Period\" = $Node.ChildNodes.Where({ $_.ClassName -EQ 'period-name'}).InnerHTML -Replace \"&lt;br&gt;\",\" \"&#13;\n    \"Temp\"   = $Node.ChildNodes.Where({ $_.ClassName -Match 'temp'}).InnerHTML&#13;\n    \"Short\"  = $Node.ChildNodes.Where({ $_.ClassName -EQ 'short-desc'}).InnerHTML -Replace \"&lt;br&gt;\",\" \"&#13;\n        # Since we don't have a class to target, on the root node, use the CSS selector p &gt; img which looks for a p element with a child img element. Next, use the Attributes property to find the one named alt and return it's value.&#13;\n    \"Alt\"    = $Node.QuerySelectorAll(\"p &gt; img\").Attributes.Where({$_.Name -EQ 'alt'}).Value&#13;\n  }&#13;\n}&#13;\n<\/code><\/pre>\n<p>\u00a0<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-8252 aligncenter\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/8219540de82a90e098bf4faa330ceb9c\/p\/uploads\/2020\/11\/8e5779e3.png\" alt=\"\" width=\"1488\" height=\"207\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Output of the parsed web page from AngleSharp.<\/p>\n<p>Although we have to iterate over a few elements to ultimately get to just the ones we want, we can walk through the HTML document structure and get to just what we need. It can be a bit tricky to understand the structures, but ultimately what AngleSharp is doing is creating objects for each DOM element. Once you figure out the best way to target the elements you need, extracting the content is not difficult.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>AngleSharp offers an excellent programmatic interface to parsing and interacting with HTML content on webpages. This can open the door to using PowerShell to retrieve content that may be otherwise inaccessible. Taking this content, storing it, and using it in scripts is extremely useful and can help aid system integration methods!\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener noreferrer\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/8249\/using-anglesharp-in-powershell-7-to-parse-webpages\/\" target=\"_blank\" rel=\"noopener noreferrer\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Using AngleSharp in PowerShell 7 to Parse Webpages \u2013 CloudSavvy IT&#8221; AngleSharp is a .NET library that makes parsing and working with HTML content quick and easy. As AngleSharp is written in .NET, you can use and consume the output in PowerShell as well. Combining these two allows you to quickly and easily script HTML&#8230;<\/p>\n","protected":false},"author":1,"featured_media":123013,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2020\/03\/23e4a5a4.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-123012","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/123012","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=123012"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/123012\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/123013"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=123012"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=123012"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=123012"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}