C# Web Scraping Tutorial (HtmlAgilityPack + Playwright)

C# web scraping tutorial with runnable code: HttpClient, HtmlAgilityPack vs AngleSharp, a pagination crawler to JSON, and Playwright for JavaScript pages.

MMotherlode Lab11 min read
Magpie title card: C# Web Scraping Tutorial (HtmlAgilityPack + Playwright)

The floor for C# web scraping is low: the HttpClient class built into .NET, twenty lines, zero packages. The ceiling is a polite crawler that walks a whole site and hands you typed JSON, and in between sit two walls: pages that build themselves with JavaScript, and sites that fingerprint your TLS handshake instead of reading your User-Agent. I ran every step below today on .NET 10.0.403 against quotes.toscrape.com, a sandbox made for this, and kept the numbers: a 1.4-second fetch, 100 quotes in 13.9 seconds, and one 403 that no User-Agent header will fix.

You get five working programs, one measured gotcha per step, and the point where selectors stop working. If you’re coming from another language, I’ve done the same drill for Python, Node.js, and Go.

What you need

  • .NET SDK 10 (the current LTS; supported until November 2028). The code runs unchanged on .NET 8 and 9; nothing here uses version-specific APIs.
  • A throwaway project: dotnet new console -o ScrapeDemo && cd ScrapeDemo.
  • Each listing below is a complete Program.cs. Paste it in, dotnet run.

The sandbox is quotes.toscrape.com: ten quotes per page, ten pages, pagination, and a JavaScript variant at /js/ for the hard case. It publishes no robots.txt (the URL 404s) and exists to be scraped. On real sites, read robots.txt and the terms of service before you point code at them.

Step 1: Fetch a page with HttpClient (zero packages)

using System.Diagnostics;

var url = "https://quotes.toscrape.com/";
var sw = Stopwatch.StartNew();
using var http = new HttpClient();
using var resp = await http.GetAsync(url);
resp.EnsureSuccessStatusCode();
var html = await resp.Content.ReadAsStringAsync();
sw.Stop();

Console.WriteLine($"{(int)resp.StatusCode} · {html.Length:N0} bytes · {sw.ElapsedMilliseconds} ms");
var titleStart = html.IndexOf("<title>") + 7;
var titleEnd = html.IndexOf("</title>", titleStart);
Console.WriteLine(html[titleStart..titleEnd]);

Output from today:

200 · 11,021 bytes · 1405 ms
Quotes to Scrape

That’s a real page in your process. The 1,405 ms is mostly network round-trips from my connection, not .NET being slow; the cold first run (with JIT) took 1,802 ms.

The gotcha: this request sends no User-Agent header at all. I pointed the same client at two echo services (postman-echo.com and httpbin.org) and both showed zero user-agent in what arrived. Plenty of CDNs score header-less requests as bots on sight. Add one line before the call:

http.DefaultRequestHeaders.UserAgent.ParseAdd("ScrapeDemo/1.0 (+mailto:[email protected])");

A declared agent with contact info reads as honest tooling; a fake Chrome string reads as something else. Which headers matter and why is its own subject.

Step 2: Parse with HtmlAgilityPack (XPath)

HtmlAgilityPack is the workhorse: version 1.13.1, MIT-licensed, about 379 million NuGet downloads, and old enough that every XPath question you’ll ever have is already answered on Stack Overflow. Install and run:

dotnet add package HtmlAgilityPack
using HtmlAgilityPack;

using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("ScrapeDemo/1.0 (+mailto:[email protected])");
var html = await http.GetStringAsync("https://quotes.toscrape.com/");

var doc = new HtmlDocument();
doc.LoadHtml(html);

var quotes = doc.DocumentNode.SelectNodes("//div[@class='quote']");
Console.WriteLine($"{quotes!.Count} quotes on the page");

foreach (var q in quotes.Take(2))
{
    var text   = HtmlEntity.DeEntitize(q.SelectSingleNode(".//span[@class='text']")!.InnerText);
    var author = HtmlEntity.DeEntitize(q.SelectSingleNode(".//small[@class='author']")!.InnerText);
    var tags   = q.SelectNodes(".//a[@class='tag']")!.Select(t => t.InnerText);
    Console.WriteLine($"{author}: {text}");
    Console.WriteLine($"  tags: {string.Join(", ", tags)}");
}
10 quotes on the page
Albert Einstein: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
  tags: change, deep-thoughts, thinking, world
J.K. Rowling: “It is our choices, Harry, that show what we truly are, far more than our abilities.”
  tags: abilities, choices

Two things I hit that the quick-start tutorials don’t mention:

  1. The API is nullable-annotated. SelectNodes and SelectSingleNode return null when the selector misses, and a modern project (<Nullable>enable</Nullable> is the default now) throws compiler warnings at every unchecked result. Those ! operators in the listing are me telling the compiler “I checked”. On a page where the selector can legitimately miss, use ?. and skip the node instead.
  2. InnerText does not decode HTML entities. A quote on page 8 is authored in the raw HTML as The question isn&#39;t who is going to let me, and InnerText hands you the &#39; untouched. HtmlEntity.DeEntitize() around it fixes that, which is why it’s in the listing. This took me a debugging round-trip to notice; the curly quotes on page 1 come through fine because they’re literal UTF-8 in the source, not entities.

Step 3: AngleSharp if you think in CSS selectors

AngleSharp is the modern alternative: version 1.9.0 stable, MIT, about 358 million downloads. It builds a real DOM you can query with querySelector-style CSS instead of XPath.

dotnet add package AngleSharp
using AngleSharp;

var context = BrowsingContext.New(Configuration.Default.WithDefaultLoader());
var doc = await context.OpenAsync("https://quotes.toscrape.com/");

var quotes = doc.QuerySelectorAll("div.quote");
Console.WriteLine($"{quotes.Length} quotes on the page");

foreach (var q in quotes.Take(2))
{
    var text   = q.QuerySelector(".text")!.TextContent;
    var author = q.QuerySelector(".author")!.TextContent;
    var tags   = q.QuerySelectorAll(".tag").Select(t => t.TextContent);
    Console.WriteLine($"{author}: {text}");
    Console.WriteLine($"  tags: {string.Join(", ", tags)}");
}

Same ten quotes, same output. One crash first, though: with plain Configuration.Default, OpenAsync returns a null document and you get a NullReferenceException that tells you nothing. AngleSharp ships without a network loader by default; WithDefaultLoader() is what lets it fetch URLs itself. (You can also parse an HttpClient string with doc = await context.OpenAsync(req => req.Content(html)) if you’d rather keep one HTTP client for the whole program.)

Entity handling is the visible difference between the two libraries. On that page-8 Ayn Rand quote, run side by side:

HAP InnerText:   “The question isn&#39;t who is going to let me; it&#39;s who is going to stop me.”
AngleSharp Text: “The question isn't who is going to let me; it's who is going to stop me.”

AngleSharp decodes entities in TextContent; HtmlAgilityPack leaves them unless you call DeEntitize. Neither is wrong. But if your output lands in a database, &#39; is forever unless you handle it at one end or the other.

Which one should you install? HAP has fifteen years of NuGet history and XPath. AngleSharp has CSS, a live DOM, and text you can store as-is. Both MIT, both alive. New code gets my vote for AngleSharp; paste-ready XPath recipes get HAP.

Step 4: Crawl the whole site into JSON

One page is a demo. A scraper follows pagination and lands the data somewhere typed. This one follows the Next link, waits a second between requests, and writes quotes.json with the built-in System.Text.Json:

using System.Diagnostics;
using System.Text.Json;
using HtmlAgilityPack;

var quotes = new List<object>();
var sw = Stopwatch.StartNew();
using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("ScrapeDemo/1.0 (+mailto:[email protected])");

var url = "https://quotes.toscrape.com/";
while (url is not null)
{
    var html = await http.GetStringAsync(url);
    var page = new HtmlDocument();
    page.LoadHtml(html);

    foreach (var q in page.DocumentNode.SelectNodes("//div[@class='quote']") ?? new HtmlNodeCollection(null))
    {
        var text = HtmlEntity.DeEntitize(q.SelectSingleNode(".//span[@class='text']")!.InnerText);
        var author = HtmlEntity.DeEntitize(q.SelectSingleNode(".//small[@class='author']")!.InnerText);
        var tags = q.SelectNodes(".//a[@class='tag']")?
                    .Select(t => HtmlEntity.DeEntitize(t.InnerText))
                    .ToArray() ?? [];
        quotes.Add(new { text, author, tags });
    }

    var next = page.DocumentNode.SelectSingleNode("//li[@class='next']/a");
    url = next is null ? null : new Uri(new Uri(url), next.GetAttributeValue("href", "")).ToString();
    await Task.Delay(1_000);                       // politeness: 1 request/second
}

Console.WriteLine($"{quotes.Count} quotes from all pages in {sw.Elapsed.TotalSeconds:0.0}s");
await File.WriteAllTextAsync("quotes.json",
    JsonSerializer.Serialize(quotes, new JsonSerializerOptions { WriteIndented = true }));
100 quotes from all pages in 13.9s

Ten pages, ten one-second waits, 25 KB of valid JSON, 50 distinct authors. If your target paginates by URL pattern instead of Next links, that variant is in the pagination guide; if you need CSV, scraping to CSV or JSON covers the formats.

The gotcha worth more than the code: three quotes on pages 3, 5, and 8 have no tags at all. The sandbox itself ships missing fields. My first draft indexed tags unconditionally and died with an ArgumentNullException on page 3. The ?? [] fallback is the fix, and the lesson generalizes: every selector is a hypothesis about a page that can change. Null-check the optional ones even on a toy site.

Step 5: Where C# web scraping stops (JavaScript pages)

Point Step 1 at https://quotes.toscrape.com/js/ and watch it “work”: 5,808 bytes, HTTP 200, and zero quote divs, because the content is injected by /static/jquery.js after your request. The page is empty and the status code lies.

That’s the wall. The fix in C# is a real browser. Playwright for .NET is Microsoft’s automation library (version 1.64.1, MIT); Puppeteer-Sharp is the port of Google’s Puppeteer and does the same job. I use Playwright because its browser installer worked first try and the API matches the JavaScript docs you’ll find when debugging:

dotnet add package Microsoft.Playwright

Install a browser once. The documented route is PowerShell:

pwsh bin/Debug/net10.0/playwright.ps1 install chromium

No pwsh on your machine? I used the library itself instead, and it worked the same: a one-off program calling Microsoft.Playwright.Program.Main(new[] { "install", "chromium" }). Either way the download is about 273 MB (a headless Chromium build in ~/.cache/ms-playwright), so do it once.

using System.Diagnostics;
using Microsoft.Playwright;

var sw = Stopwatch.StartNew();
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://quotes.toscrape.com/js/");
var quotes = await page.Locator("div.quote").AllAsync();
sw.Stop();

Console.WriteLine($"{quotes.Count} quotes rendered in {sw.Elapsed.TotalSeconds:0.0}s");
var first = await quotes[0].Locator(".text").TextContentAsync();
Console.WriteLine(first);
10 quotes rendered in 2.7s
“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”

Ten quotes where the static fetch got zero. The cost is real, though: 2.7 seconds and a browser launch for one page against 1.4 seconds for one static page. Subsequent pages in the same browser skip the launch, so the pattern that keeps this sane is one browser, many pages: launch once, open tabs in a loop, close at the end. When to pay that cost, and what else lives on the other side of it, is the subject of the dynamic-sites guide and Playwright itself.

What the tutorials skip

One HttpClient per program, not per request. Every listing above makes one client and keeps it, and that’s the pattern to keep under load: new HttpClient() per request exhausts sockets (the classic TIME_WAIT pile-up); a single static client or IHttpClientFactory for anything long-running.

Async all the way down. Top-level await makes console apps easy, and you should never see .Result or .Wait() in new code; those block and can deadlock in older ASP.NET contexts. Every listing here is async-native because HttpClient is.

Rate limiting beyond Task.Delay. A fixed one-second sleep is fine for a walk of one site. For burst control, .NET has shipped System.Threading.RateLimiter since .NET 7, a token-bucket in about five lines, and it composes better than sleeps scattered through loops.

The TLS-fingerprint wall, measured. Stack Overflow sits behind Cloudflare. I fetched a question page with plain HttpClient wearing a real Chrome User-Agent string:

403 · 5,709 bytes · 327 ms  →  Cloudflare challenge page

The header said Chrome; the TLS handshake said .NET, and Cloudflare believed the handshake. No User-Agent line fixes this class of block. Your honest options are: scrape sources that don’t do this, use the site’s API, or pay a scraping API that solves challenges for you. Not getting blocked is a strategy problem, not a header problem.

Dead libraries. You’ll find CsQuery and ScrapySharp in older answers. CsQuery’s last stable release is from 2013. ScrapySharp’s NuGet registration feed hasn’t changed since February 2020. Both still install; neither should start your project in 2026.

If you’d rather not write selectors

When the deliverable is the text itself (feeding an LLM, archiving articles, taking notes), a scraper is overkill. Magpie, a Go CLI in the same spirit as this tutorial, does magpie scrape https://quotes.toscrape.com/ and returns cleaned Markdown with the boilerplate already gone, no selector code at all (AGPL-3.0-or-later, or a commercial license). The C# route in this article wins when you need typed records (authors, tags, prices as fields), not prose. Pick by the shape of your output.

FAQ

Is C# good for web scraping? Yes, especially if .NET is already your stack: HttpClient is fast and async-native, System.Text.Json is built in, and the result is a typed, compilable program. The scraping-library ecosystem is smaller than Python’s, so fewer site-specific recipes exist.

HtmlAgilityPack or AngleSharp? Both MIT-licensed and maintained. HAP brings XPath and fifteen years of accumulated answers on NuGet and Stack Overflow; AngleSharp brings CSS selectors, a live DOM, and entity-decoded text out of the box. I reach for AngleSharp in new code and HAP when following an XPath recipe.

Is web scraping legal in C#? The language is irrelevant to the legality. Public data, respect robots.txt and terms of service, don’t scrape behind logins you don’t own, and mind copyright and personal-data rules for what you store. This is context, not legal advice.

How do I scrape JavaScript pages in C#? Run a browser: Playwright for .NET rendered a page that static fetching returned empty (0 quotes → 10). First check whether the data ships as JSON anyway; many “JavaScript pages” load it from an API your HttpClient can call directly.

How do I keep a C# scraper from getting blocked? Declare a real User-Agent with contact info, keep requests to one per second or slower, honor robots.txt, and cache what you fetch. When blocks are TLS-based (like Stack Overflow’s), no header helps: change source, API, or tooling.

Start at the wall

Run the Step 4 crawler against your real target with the sandbox selectors swapped for yours. If it fills your JSON file, you’re done: schedule it with cron and stop reading. The moment a page comes back with zero records, you know which wall you hit: a selector miss means Step 2, an empty shell means Step 5, and a 403 means it’s time for a different source. That diagnosis is the whole skill.

Stop renting credits.

One flat price, your machine, your keys.

Download free for Windows, macOS and Linux

Windows · macOS · Linux $49/mo flat, cancel anytime