Web scraping
suggest changeWeb scraping means downloading web pages and pulling structured data out of their HTML: prices from a shop, a table from Wikipedia, job listings, links for a crawler. A scraper in C# usually has three parts:
- fetch:
HttpClientdownloads the page (see Performing HTTP requests) - parse: an HTML parser turns the markup into a DOM tree you can query with CSS selectors or XPath
- extract and store: convert text to numbers and dates, resolve relative links, save to JSON, CSV or a database
.NET has no HTML parser built in. The two libraries everyone uses are:
| Library | Query language | Notes |
|---|---|---|
| AngleSharp | CSS selectors | Parses HTML the way browsers do (HTML5 spec), has a full DOM API, async loading |
| HtmlAgilityPack | XPath | Older, very popular, forgiving, small |
For pages whose content is created by JavaScript you need a real browser, driven by Playwright.
Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs). Examples that fetch pages start a small local ASP.NET Core server in the same program, so they're self-contained and don't depend on a real website changing its markup.
Parsing HTML with AngleSharp
HtmlParser.ParseDocument takes a string or a stream and returns an IHtmlDocument. QuerySelector returns the first matching element or null, and QuerySelectorAll returns all matches:
#:package AngleSharp@1.8.5
using AngleSharp;
using AngleSharp.Html.Parser;
string html = """
<html><head><title>Books & More</title></head>
<body>
<ul id="books">
<li class="book" data-id="17">
<a href="/book/17">Clean Code</a> <span class="price">$31.50</span>
</li>
<li class="book sale" data-id="42">
<a href="/book/42">The Pragmatic Programmer</a> <span class="price">$25.00</span>
</li>
<li class="book" data-id="7">
<a href="https://other.example/book/7">Refactoring<a> <span class="price">$40.10</span>
</ul>
</body></html>
""";
var parser = new HtmlParser();
var doc = parser.ParseDocument(html);
Console.WriteLine($"Title: {doc.Title}");
foreach (var li in doc.QuerySelectorAll("#books > li.book"))
{
var link = li.QuerySelector("a")!;
string price = li.QuerySelector(".price")?.TextContent.Trim() ?? "?";
bool onSale = li.ClassList.Contains("sale");
Console.WriteLine($"{li.GetAttribute("data-id"),3} | {link.TextContent,-26} | {link.GetAttribute("href"),-29} | {price}{(onSale ? " (sale)" : "")}");
}
Console.WriteLine(doc.QuerySelector("li[data-id='42'] .price")?.TextContent);
Console.WriteLine(doc.QuerySelectorAll("li.book").Length);
Title: Books & More
17 | Clean Code | /book/17 | $31.50
42 | The Pragmatic Programmer | /book/42 | $25.00 (sale)
7 | Refactoring | https://other.example/book/7 | $40.10
$25.00
3
Things to note:
- The HTML is broken on purpose: the last
<a>and<li>are never closed. AngleSharp repairs it exactly like a browser would, so selectors that work in the browser's DevTools work here too. TextContentreturns decoded text (&becomes&) including whitespace from the source, so you almost always want.Trim().GetAttributereturns the raw attribute value ornullwhen it's missing.ClassList,IdandDatasetare also available.- Any CSS selector works: descendant (
li .price), child (ul > li), attributes ([data-id='42'],a[href^='https']), pseudo-classes (:nth-child(2),:not(.ad)).
The fastest way to find a selector is to right-click the element in the browser, choose Inspect, then right-click the node and Copy > Copy selector. The generated selector is usually too specific (body > div:nth-child(3) > ...), so simplify it to rely on ids, classes and data- attributes, which change less often than the layout.
Resolving relative links
Links in HTML are usually relative. To follow them you need the page's address. If you load the document through a BrowsingContext with an address, AngleSharp knows the base URL and the typed IHtmlAnchorElement.Href property returns an absolute URL. It also honors a <base href> tag, which new Uri(pageUri, href) doesn't know about:
#:package AngleSharp@1.8.5
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
string html = """
<base href="/shop/">
<a href="item?id=1">relative</a>
<a href="/about">root-relative</a>
<a href="../img/logo.png">parent</a>
<a href="//cdn.example.net/x.js">protocol-relative</a>
<a href="mailto:hi@example.com">mail</a>
<a href="#top">fragment</a>
<a>no href</a>
""";
var context = BrowsingContext.New(Configuration.Default);
IDocument doc = await context.OpenAsync(req => req
.Content(html)
.Address("https://example.com/catalog/page2.html"));
Console.WriteLine($"BaseUri: {doc.BaseUri}");
foreach (var a in doc.QuerySelectorAll<IHtmlAnchorElement>("a"))
{
Console.WriteLine($"{a.GetAttribute("href") ?? "(null)",-26} -> {a.Href}");
}
// Without AngleSharp: System.Uri does the same resolution
var page = new Uri("https://example.com/catalog/page2.html");
Console.WriteLine(new Uri(page, "../img/logo.png"));
Console.WriteLine(new Uri(page, "item?id=1"));
BaseUri: https://example.com/shop/
item?id=1 -> https://example.com/shop/item?id=1
/about -> https://example.com/about
../img/logo.png -> https://example.com/img/logo.png
//cdn.example.net/x.js -> https://cdn.example.net/x.js
mailto:hi@example.com -> mailto:hi@example.com
#top -> https://example.com/shop/#top
(null) ->
https://example.com/img/logo.png
https://example.com/catalog/item?id=1
GetAttribute("href") gives what's in the markup, while Href gives the resolved URL. The two System.Uri lines show that without the <base> tag item?id=1 resolves against /catalog/ instead of /shop/. If you use plain new Uri(page, href), check for a <base> element first. Also filter out mailto:, javascript: and tel: links before trying to download them.
The generic QuerySelectorAll<T> and QuerySelector<T> extension methods are in the AngleSharp.Dom namespace. They return typed elements such as IHtmlAnchorElement, IHtmlInputElement or IHtmlTableElement.
XPath with HtmlAgilityPack
HtmlAgilityPack (HAP) uses XPath, which can do things CSS can't, for example selecting by text or walking to a preceding sibling. This example extracts a table:
#:package HtmlAgilityPack@1.13.1
using System.Globalization;
using System.Net;
using HtmlAgilityPack;
string html = """
<table id="prices">
<thead><tr><th>Symbol</th><th>Name</th><th>Price</th><th>Change</th></tr></thead>
<tbody>
<tr><td>MSFT</td><td>Microsoft</td><td>512.30</td><td class="up">+1.2%</td></tr>
<tr><td>AAPL</td><td>Apple Inc.</td><td>231.05</td><td class="down">-0.4%</td></tr>
<tr><td>AT&T</td><td>AT&T Inc.</td><td>27.80</td><td class="up">+0.1%</td></tr>
<tr class="ad"><td colspan="4">Sponsored</td></tr>
</tbody>
</table>
""";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var headers = doc.DocumentNode
.SelectNodes("//table[@id='prices']/thead/tr/th")!
.Select(th => th.InnerText.Trim())
.ToList();
Console.WriteLine(string.Join(" | ", headers));
var rows = doc.DocumentNode.SelectNodes("//table[@id='prices']/tbody/tr[not(@class='ad')]")!;
foreach (var tr in rows)
{
var cells = tr.SelectNodes("td")!
.Select(td => WebUtility.HtmlDecode(td.InnerText).Trim())
.ToArray();
decimal price = decimal.Parse(cells[2], CultureInfo.InvariantCulture);
Console.WriteLine($"{cells[0],-5} {cells[1],-12} {price,8:F2} {cells[3]}");
}
// SelectNodes returns null (not an empty list) when nothing matches
var none = doc.DocumentNode.SelectNodes("//div[@class='missing']");
Console.WriteLine(none is null ? "no match -> null" : $"{none.Count} matches");
// Attribute and text queries
var up = doc.DocumentNode.SelectNodes("//td[@class='up']/preceding-sibling::td[3]")!;
Console.WriteLine("Rising: " + string.Join(", ", up.Select(n => HtmlEntity.DeEntitize(n.InnerText))));
Console.WriteLine("Raw InnerText: " + doc.DocumentNode.SelectSingleNode("//tbody/tr[3]/td[1]")!.InnerText);
Symbol | Name | Price | Change
MSFT Microsoft 512.30 +1.2%
AAPL AppleĀ Inc. 231.05 -0.4%
AT&T AT&T Inc. 27.80 +0.1%
no match -> null
Rising: MSFT, AT&T
Raw InnerText: AT&T
HtmlAgilityPack has a few traps:
SelectNodesreturnsnull, not an empty collection, when nothing matches. Use?.or?? [], or!if the element must exist.InnerTextis not HTML-decoded:AT&TstaysAT&T. Decode withWebUtility.HtmlDecodeorHtmlEntity.DeEntitize.- A
decodes to U+00A0 (no-break space), not a normal space.Trim()removes it at the ends, but inside a string it breaks comparisons like== "Apple Inc.". Replace'\u00A0'with' 'if that matters. - Parse numbers with
CultureInfo.InvariantCulture, otherwise512.30turns into51230on a machine with a German or Polish locale.
XPath predicates such as tr[not(@class='ad')] and axes such as preceding-sibling::td[3] (the third td before this one, counting backwards) are handy for skipping rows and for finding a label next to a value. For CSS-style queries on HAP documents there's the Fizzler package, but if you prefer CSS selectors it's simpler to use AngleSharp.
A complete scraper with pagination
A real scraper fetches a listing page, extracts the items, finds the "next page" link and repeats. This program scrapes all products from a paginated test shop and serializes them to JSON:
#:sdk Microsoft.NET.Sdk.Web
#:package AngleSharp@1.8.5
#:property PublishAot=false
using System.Globalization;
using System.Net;
using System.Text.Json;
using AngleSharp.Html.Parser;
// ---------- a fake shop to scrape (3 pages of products) ----------
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5281");
string[][] products =
[
["Keyboard", "49.99"], ["Mouse", "19.50"], ["Monitor", "189.00"],
["Webcam", "64.25"], ["Headset", "79.00"], ["USB hub", "15.75"], ["Dock", "129.90"],
];
app.MapGet("/products", (int? page, HttpRequest req) =>
{
int p = page ?? 1;
var items = products.Skip((p - 1) * 3).Take(3)
.Select((x, i) => $"""
<div class="product"><h2><a href="/products/{(p - 1) * 3 + i + 1}">{x[0]}</a></h2>
<span class="price">${x[1]}</span></div>
""");
string next = p * 3 < products.Length ? $"""<a rel="next" href="?page={p + 1}">Next</a>""" : "";
Console.WriteLine($" [server] GET {req.Path}{req.QueryString} UA={req.Headers.UserAgent}");
return Results.Content($"<html><body>{string.Concat(items)}{next}</body></html>", "text/html; charset=utf-8");
});
await app.StartAsync();
// ---------- the scraper ----------
using var http = new HttpClient(new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.All,
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
})
{
Timeout = TimeSpan.FromSeconds(30),
};
http.DefaultRequestHeaders.UserAgent.ParseAdd("BookScraper/1.0 (+https://example.com/bot)");
http.DefaultRequestHeaders.Accept.ParseAdd("text/html");
var parser = new HtmlParser();
var results = new List<Product>();
Uri? url = new("http://localhost:5281/products");
while (url is not null)
{
using var resp = await http.GetAsync(url);
resp.EnsureSuccessStatusCode();
await using var stream = await resp.Content.ReadAsStreamAsync();
var doc = await parser.ParseDocumentAsync(stream);
foreach (var div in doc.QuerySelectorAll("div.product"))
{
var a = div.QuerySelector("h2 a")!;
string priceText = div.QuerySelector(".price")!.TextContent.Trim().TrimStart('$');
results.Add(new Product(
a.TextContent.Trim(),
decimal.Parse(priceText, CultureInfo.InvariantCulture),
new Uri(url, a.GetAttribute("href")!).ToString()));
}
string? next = doc.QuerySelector("a[rel=next]")?.GetAttribute("href");
url = next is null ? null : new Uri(url, next);
await Task.Delay(TimeSpan.FromMilliseconds(500)); // be polite
}
Console.WriteLine($"Scraped {results.Count} products, total {results.Sum(p => p.Price):F2}");
Console.WriteLine(JsonSerializer.Serialize(results.Take(2), new JsonSerializerOptions { WriteIndented = true }));
await app.StopAsync();
record Product(string Name, decimal Price, string Url);
[server] GET /products UA=BookScraper/1.0 (+https://example.com/bot)
[server] GET /products?page=2 UA=BookScraper/1.0 (+https://example.com/bot)
[server] GET /products?page=3 UA=BookScraper/1.0 (+https://example.com/bot)
Scraped 7 products, total 547.39
[
{
"Name": "Keyboard",
"Price": 49.99,
"Url": "http://localhost:5281/products/1"
},
{
"Name": "Mouse",
"Price": 19.50,
"Url": "http://localhost:5281/products/2"
}
]
What makes this a well-behaved scraper:
- One
HttpClientfor the whole run. Creating one per request exhausts sockets.PooledConnectionLifetimemakes long-running scrapers pick up DNS changes. - An honest
User-Agentwith a way to contact you. The defaultHttpClientsends noUser-Agentat all, and many sites reject or throttle such requests. AutomaticDecompressionasks for gzip/brotli and decompresses transparently. Pages download several times faster.- A
Timeoutso one hung server doesn't stop the run. - A delay between requests. Hammering a site with requests is the quickest way to get blocked, and it costs the owner money.
- Streaming into the parser.
ParseDocumentAsync(stream)lets AngleSharp detect the encoding from a<meta charset>tag when theContent-Typeheader doesn't say.ReadAsStringAsyncrelies only on the header and falls back to UTF-8. - The loop stops when there's no
rel="next"link. Add a page limit too, because some sites have a "next" link on the last page that points to itself.
The #:property PublishAot=false line is needed because file-based programs default to Native AOT, where reflection-based JsonSerializer is disabled. In a normal project you don't need it.
Crawling a site concurrently
A crawler starts from one page and follows links, keeping track of what it has seen. This version crawls level by level with at most 4 requests in flight, stays on the same host, drops #fragments so api and api#usage count as one page, and obeys robots.txt:
#:sdk Microsoft.NET.Sdk.Web
#:package AngleSharp@1.8.5
#:property PublishAot=false
using System.Collections.Concurrent;
using AngleSharp.Html.Parser;
// ---------- a small site: pages link to each other ----------
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5282");
var site = new Dictionary<string, string>
{
["/"] = """<a href="/docs/">Docs</a> <a href="/blog/">Blog</a> <a href="https://github.com/x">GitHub</a>""",
["/docs/"] = """<a href="intro">Intro</a> <a href="api">API</a> <a href="/">Home</a>""",
["/docs/intro"] = """<a href="api">API</a> <a href="/private/admin">Admin</a>""",
["/docs/api"] = """<a href="intro#usage">Intro</a> <a href="/missing">Broken</a>""",
["/blog/"] = """<a href="/blog/post-1">Post 1</a> <a href="/docs/api">API</a>""",
["/blog/post-1"] = """<a href="/blog/">Blog</a>""",
["/private/admin"] = "secret",
};
app.MapGet("/robots.txt", () => "User-agent: *\nDisallow: /private/\n");
app.MapFallback((HttpContext ctx) =>
site.TryGetValue(ctx.Request.Path, out var body)
? Results.Content($"<html><head><title>{ctx.Request.Path}</title></head><body>{body}</body></html>", "text/html")
: Results.NotFound());
await app.StartAsync();
// ---------- the crawler ----------
var root = new Uri("http://localhost:5282/");
using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("MiniCrawler/1.0");
string[] disallowed = await LoadRobotsAsync(http, root);
Console.WriteLine($"robots.txt disallows: {string.Join(", ", disallowed)}");
var parser = new HtmlParser();
var seen = new ConcurrentDictionary<string, bool>();
var report = new ConcurrentBag<string>();
var frontier = new List<Uri> { root };
seen[root.AbsoluteUri] = true;
const int maxPages = 50;
for (int depth = 0; frontier.Count > 0 && seen.Count < maxPages; depth++)
{
var next = new ConcurrentBag<Uri>();
await Parallel.ForEachAsync(frontier, new ParallelOptions { MaxDegreeOfParallelism = 4 },
async (url, ct) =>
{
using var resp = await http.GetAsync(url, ct);
if (!resp.IsSuccessStatusCode)
{
report.Add($"{(int)resp.StatusCode} {url.AbsolutePath}");
return;
}
if (resp.Content.Headers.ContentType?.MediaType != "text/html") return;
var doc = await parser.ParseDocumentAsync(await resp.Content.ReadAsStringAsync(ct));
report.Add($"200 {url.AbsolutePath} (depth {depth}, title \"{doc.Title}\")");
foreach (var a in doc.QuerySelectorAll("a[href]"))
{
if (!Uri.TryCreate(url, a.GetAttribute("href"), out var link)) continue;
link = new UriBuilder(link) { Fragment = "" }.Uri; // drop #fragment
if (link.Host != root.Host || link.Scheme != root.Scheme) continue; // stay on site
if (disallowed.Any(p => link.AbsolutePath.StartsWith(p))) continue; // obey robots.txt
if (seen.TryAdd(link.AbsoluteUri, true)) next.Add(link);
}
});
frontier = next.ToList();
}
foreach (var line in report.OrderBy(l => l.Split(' ')[1], StringComparer.Ordinal)) Console.WriteLine(line);
await app.StopAsync();
static async Task<string[]> LoadRobotsAsync(HttpClient http, Uri root)
{
try
{
string txt = await http.GetStringAsync(new Uri(root, "/robots.txt"));
bool forAll = false;
var rules = new List<string>();
foreach (var raw in txt.Split('\n'))
{
var line = raw.Split('#')[0].Trim();
if (line.StartsWith("User-agent:", StringComparison.OrdinalIgnoreCase))
forAll = line[11..].Trim() == "*";
else if (forAll && line.StartsWith("Disallow:", StringComparison.OrdinalIgnoreCase)
&& line[9..].Trim() is { Length: > 0 } path)
rules.Add(path);
}
return rules.ToArray();
}
catch (HttpRequestException) { return []; } // no robots.txt: everything allowed
}
robots.txt disallows: /private/
200 / (depth 0, title "/")
200 /blog/ (depth 1, title "/blog/")
200 /blog/post-1 (depth 2, title "/blog/post-1")
200 /docs/ (depth 1, title "/docs/")
200 /docs/api (depth 2, title "/docs/api")
200 /docs/intro (depth 2, title "/docs/intro")
404 /missing
Notes:
Parallel.ForEachAsyncwithMaxDegreeOfParallelismcaps concurrent requests (see Parallel.ForEach).ConcurrentDictionary.TryAddis an atomic "check and mark as seen", so no page is queued twice even when two workers find the same link at the same time./private/adminis linked from/docs/introbut never fetched becauserobots.txtdisallows it. The GitHub link is skipped because it's on another host. The broken/missinglink shows up as a 404, which makes a crawler like this useful for checking your own site for dead links.- Check
Content-Typebefore parsing so you don't feed PDFs and images to the HTML parser. - The
robots.txtparser here handles onlyUser-agent: *andDisallowprefixes. The real format also hasAllow, wildcards (*,$), groups for specific bots andCrawl-delay. For production, use a library or implement the rules from RFC 9309. - Always limit the total number of pages. Calendars, faceted search and session ids in URLs can generate an infinite number of distinct links.
Retries, rate limits and Retry-After
Sites answer 429 Too Many Requests or 503 Service Unavailable when you go too fast, often with a Retry-After header saying how long to wait. Retry transient errors with backoff and give up on the rest:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Diagnostics;
using System.Net;
// ---------- a rate-limited server: the first two requests get 429 ----------
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5283");
int hits = 0;
app.MapGet("/data", (HttpResponse res) =>
{
if (Interlocked.Increment(ref hits) <= 2)
{
res.Headers.RetryAfter = "1";
return Results.StatusCode(429);
}
return Results.Text("<p>finally</p>", "text/html");
});
await app.StartAsync();
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
var sw = Stopwatch.StartNew();
string html = await GetWithRetryAsync(http, new Uri("http://localhost:5283/data"));
Console.WriteLine($"{html} (server saw {hits} requests, {sw.Elapsed.TotalSeconds >= 2})");
await app.StopAsync();
static async Task<string> GetWithRetryAsync(HttpClient http, Uri url, int maxAttempts = 5)
{
for (int attempt = 1; ; attempt++)
{
TimeSpan delay;
try
{
using var resp = await http.GetAsync(url);
if (resp.IsSuccessStatusCode)
return await resp.Content.ReadAsStringAsync();
bool transient = resp.StatusCode is HttpStatusCode.TooManyRequests
or HttpStatusCode.ServiceUnavailable or HttpStatusCode.BadGateway
or HttpStatusCode.GatewayTimeout;
if (!transient || attempt == maxAttempts)
resp.EnsureSuccessStatusCode(); // throws HttpRequestException
// honor Retry-After (seconds or a date), otherwise exponential backoff
delay = resp.Headers.RetryAfter?.Delta
?? (resp.Headers.RetryAfter?.Date - DateTimeOffset.UtcNow)
?? TimeSpan.FromSeconds(Math.Pow(2, attempt));
Console.WriteLine($"attempt {attempt}: {(int)resp.StatusCode}, waiting {delay.TotalSeconds}s");
}
catch (HttpRequestException ex) when (ex.StatusCode is null && attempt < maxAttempts)
{
delay = TimeSpan.FromSeconds(Math.Pow(2, attempt)); // network error
Console.WriteLine($"attempt {attempt}: {ex.Message}, waiting {delay.TotalSeconds}s");
}
await Task.Delay(delay + TimeSpan.FromMilliseconds(Random.Shared.Next(0, 250))); // jitter
}
}
attempt 1: 429, waiting 1s
attempt 2: 429, waiting 1s
<p>finally</p> (server saw 3 requests, True)
RetryConditionHeaderValue exposes Retry-After either as Delta (seconds) or as Date. Without it, the wait doubles each attempt (2s, 4s, 8s...), and a little random jitter keeps many workers from retrying in lockstep. Don't retry 404 or 403: a page that doesn't exist or that blocks you won't change in a few seconds.
In an app that uses IHttpClientFactory, the Microsoft.Extensions.Http.Resilience package gives you the same thing (retry with backoff, Retry-After support, circuit breaker, timeouts) with one call: services.AddHttpClient("scraper").AddStandardResilienceHandler().
Logging in and submitting forms
Pages behind a login need cookies and, usually, a hidden anti-forgery token from the login form. The pattern is: GET the form, collect all its fields (including hidden ones), fill in your values, POST, and keep the cookies for later requests:
#:sdk Microsoft.NET.Sdk.Web
#:package AngleSharp@1.8.5
#:property PublishAot=false
using System.Net;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
// ---------- a site with a login form protected by a CSRF token ----------
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5284");
app.MapGet("/login", (HttpResponse res) =>
{
string token = Guid.NewGuid().ToString("N")[..12];
res.Cookies.Append("csrf", token);
return Results.Content($"""
<form action="/login" method="post">
<input type="hidden" name="csrf_token" value="{token}">
<input name="username"> <input type="password" name="password">
<input type="checkbox" name="remember" value="yes" checked>
<button>Sign in</button>
</form>
""", "text/html");
});
app.MapPost("/login", (HttpRequest req, HttpResponse res) =>
{
var f = req.Form;
if (f["csrf_token"] != req.Cookies["csrf"]) return Results.BadRequest("bad CSRF token");
if (f["username"] != "alice" || f["password"] != "pa55") return Results.Unauthorized();
res.Cookies.Append("session", "alice-session", new() { HttpOnly = true });
return Results.Redirect("/account");
});
app.MapGet("/account", (HttpRequest req) => req.Cookies["session"] is null
? Results.Redirect("/login")
: Results.Content("<h1 class='welcome'>Welcome back, alice</h1><td id='balance'>$1,024.00</td>", "text/html"));
await app.StartAsync();
// ---------- the scraper ----------
var baseUri = new Uri("http://localhost:5284/");
var cookies = new CookieContainer();
using var http = new HttpClient(new HttpClientHandler { CookieContainer = cookies }) { BaseAddress = baseUri };
var parser = new HtmlParser();
// 1. GET the form; collect every field, including hidden ones, with their default values
var loginPage = await parser.ParseDocumentAsync(await http.GetStringAsync("/login"));
var form = loginPage.QuerySelector<IHtmlFormElement>("form")!;
var fields = new Dictionary<string, string>();
foreach (var input in form.QuerySelectorAll<IHtmlInputElement>("input[name]"))
{
if (input.Type is "checkbox" or "radio" && !input.IsChecked) continue;
fields[input.Name!] = input.Value;
}
Console.WriteLine("Form fields: " + string.Join(", ", fields.Select(kv => $"{kv.Key}='{kv.Value}'")));
// 2. fill in credentials and POST to the form's action
fields["username"] = "alice";
fields["password"] = "pa55";
string action = form.GetAttribute("action") ?? "/login";
using var resp = await http.PostAsync(action, new FormUrlEncodedContent(fields));
Console.WriteLine($"POST -> {(int)resp.StatusCode}, landed on {resp.RequestMessage!.RequestUri!.AbsolutePath}");
// 3. the session cookie is in the jar, so protected pages work
var account = await parser.ParseDocumentAsync(await resp.Content.ReadAsStringAsync());
Console.WriteLine(account.QuerySelector(".welcome")?.TextContent);
Console.WriteLine("Cookies: " + string.Join("; ", cookies.GetCookies(baseUri).Select(c => c.Name)));
await app.StopAsync();
Form fields: csrf_token='c8c6ae9bc360', username='', password='', remember='yes'
POST -> 200, landed on /account
Welcome back, alice
Cookies: csrf; session
The token is random, so it differs on each run. Key points:
- Use one
HttpClientwith aCookieContainerfor the whole session. It stores thecsrfandsessioncookies and sends them back automatically (see Cookies). - Copy all form inputs, not just the ones you can see. Missing hidden fields (CSRF tokens, ASP.NET
__VIEWSTATE,__EVENTVALIDATION) are the most common reason a scripted login fails. Unchecked checkboxes and radio buttons aren't submitted by browsers, so skip them too. HttpClientfollows the302redirect after the POST automatically.resp.RequestMessage.RequestUritells you where you ended up, which is a cheap way to detect a failed login (you land back on/login).FormUrlEncodedContentsendsapplication/x-www-form-urlencoded, which is what a plain HTML form posts. For forms withenctype="multipart/form-data", useMultipartFormDataContent.
Only log in to sites with an account you're allowed to use this way, and never store passwords in source code: read them from environment variables or user secrets.
Look for data before parsing HTML
Before writing selectors, check whether the data is already available in a machine-readable form:
- Open the browser's DevTools, Network tab, filter by Fetch/XHR and reload. If the page loads its data from a JSON API, call that API with
HttpClientandGetFromJsonAsync. That's faster and far more stable than parsing HTML. - Look for an official API, an RSS/Atom feed or a
sitemap.xml. - Look in the page source for
<script type="application/ld+json">(schema.org data that shops, recipe sites and news sites add for search engines) or for state embedded by JavaScript frameworks, such as Next.js__NEXT_DATA__.
#:package AngleSharp@1.8.5
using System.Text.Json;
using AngleSharp.Html.Parser;
string html = """
<html><head>
<script type="application/ld+json">
{ "@context": "https://schema.org", "@type": "Product",
"name": "Noise-cancelling headphones", "sku": "NC-700",
"offers": { "@type": "Offer", "price": "279.00", "priceCurrency": "EUR",
"availability": "https://schema.org/InStock" },
"aggregateRating": { "ratingValue": 4.6, "reviewCount": 1873 } }
</script>
<script id="__NEXT_DATA__" type="application/json">
{"props":{"pageProps":{"variants":[{"color":"black","stock":12},{"color":"silver","stock":0}]}}}
</script>
</head><body><div id="root"></div></body></html>
""";
var doc = new HtmlParser().ParseDocument(html);
// schema.org structured data, used by many shops and news sites for search engines
foreach (var script in doc.QuerySelectorAll("script[type='application/ld+json']"))
{
using var json = JsonDocument.Parse(script.TextContent);
var root = json.RootElement;
if (root.GetProperty("@type").GetString() != "Product") continue;
var offer = root.GetProperty("offers");
Console.WriteLine($"{root.GetProperty("name")} ({root.GetProperty("sku")})");
Console.WriteLine($" {offer.GetProperty("price")} {offer.GetProperty("priceCurrency")}, " +
$"{offer.GetProperty("availability").GetString()!.Split('/')[^1]}");
var rating = root.GetProperty("aggregateRating");
Console.WriteLine($" rated {rating.GetProperty("ratingValue")} by {rating.GetProperty("reviewCount")} people");
}
// state embedded by a JavaScript framework (Next.js here)
string? state = doc.QuerySelector("#__NEXT_DATA__")?.TextContent;
if (state is not null)
{
var variants = JsonDocument.Parse(state).RootElement
.GetProperty("props").GetProperty("pageProps").GetProperty("variants");
foreach (var v in variants.EnumerateArray())
Console.WriteLine($" variant {v.GetProperty("color")}: {v.GetProperty("stock")} in stock");
}
Noise-cancelling headphones (NC-700)
279.00 EUR, InStock
rated 4.6 by 1873 people
variant black: 12 in stock
variant silver: 0 in stock
The JSON in a <script> element isn't HTML, so read it with TextContent and parse it with System.Text.Json (see JSON handling). Structured data has a documented schema and doesn't change when the site is redesigned, which makes it much more reliable than div.price > span:nth-child(2).
Pages rendered by JavaScript
If the HTML you download contains only an empty <div id="root"> or "Loading...", the content is created by JavaScript in the browser. HttpClient doesn't run scripts, so you have to either call the JSON API the page uses (see above) or drive a real browser with Playwright:
#:sdk Microsoft.NET.Sdk.Web
#:package Microsoft.Playwright@1.63.0
#:property PublishAot=false
using Microsoft.Playwright;
// ---------- a page whose content is rendered by JavaScript ----------
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5285");
app.MapGet("/", () => Results.Content("""
<html><body><ul id="list">Loading...</ul>
<script>
setTimeout(async () => {
const items = await (await fetch('/api/items')).json();
document.getElementById('list').innerHTML =
items.map(i => `<li class="item">${i.name}: ${i.price}</li>`).join('');
}, 300);
</script></body></html>
""", "text/html"));
app.MapGet("/api/items", () => new[] { new { name = "Tea", price = 3.5 }, new { name = "Coffee", price = 4.2 } });
await app.StartAsync();
// plain HttpClient only sees the placeholder
using var http = new HttpClient();
string raw = await http.GetStringAsync("http://localhost:5285/");
Console.WriteLine($"HttpClient sees 'Tea': {raw.Contains("Tea")}");
// a real browser runs the script
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(new() { Headless = true, Channel = "msedge" });
var page = await browser.NewPageAsync(new() { UserAgent = "ShopScraper/1.0" });
await page.GotoAsync("http://localhost:5285/");
await page.Locator("li.item").First.WaitForAsync(); // wait until the JS has rendered
foreach (string text in await page.Locator("li.item").AllInnerTextsAsync())
Console.WriteLine(text);
// the rendered DOM can also be handed to AngleSharp or HtmlAgilityPack
string rendered = await page.ContentAsync();
Console.WriteLine($"Rendered HTML contains 'Tea': {rendered.Contains("<li class=\"item\">Tea")}");
await app.StopAsync();
HttpClient sees 'Tea': False
Tea: 3.5
Coffee: 4.2
Rendered HTML contains 'Tea': True
Playwright needs a browser. Channel = "msedge" (or "chrome") uses the one installed on the machine. To use the bundled Chromium instead, build once and run pwsh bin/Debug/net10.0/playwright.ps1 install chromium, then drop the Channel option.
Locators wait automatically: WaitForAsync returns as soon as the first li.item exists, so there's no need for Task.Delay guessing. Playwright can also click buttons, fill forms, scroll to load more items and take screenshots. A browser is, however, 10 to 100 times slower and heavier than HttpClient, so use it only when there's no other way to get the data.
Why not regular expressions
It's tempting to grab values with a regex like <span class="price">(.*?)</span>. It breaks as soon as the site adds another class (class="price sale"), swaps attribute order, uses single quotes, adds a newline or a nested <b>, or puts an entity like € in the text. An HTML parser handles all of that. Regex is fine for a second step: extracting 31.50 from the text "Price: $31.50 incl. VAT" that a selector already found.
Scraping responsibly
- Read the site's terms of service and
robots.txt. Prefer an official API when one exists. - Keep request rates low (one request per second or slower for small sites), scrape during off-peak hours, and cache pages you've already downloaded instead of fetching them again.
- Identify your bot in the
User-Agentand include contact information. - Don't collect personal data unless you have a legal basis for it (GDPR and similar laws apply to scraped data too), and respect copyright when republishing content.
- Expect selectors to break. Validate what you extract (for example, fail loudly when a page yields zero products) so a site redesign doesn't silently fill your database with empty values.
Summary
- Fetch with a single, long-lived
HttpClientthat has aUser-Agent, a timeout and automatic decompression. - Parse with AngleSharp (CSS selectors, browser-accurate parsing) or HtmlAgilityPack (XPath). Never parse HTML with regex.
- Resolve links with
IHtmlAnchorElement.Hrefornew Uri(pageUri, href), and parse numbers withCultureInfo.InvariantCulture. - Follow
rel="next"links for pagination, deduplicate URLs for crawling, cap concurrency withParallel.ForEachAsync, and limit the total page count. - Retry 429/5xx with backoff and honor
Retry-After. Respectrobots.txt. - Use a
CookieContainerand copy all form fields, including hidden tokens, to log in. - Check for JSON APIs, JSON-LD and embedded state before writing selectors, and use Playwright only for pages that need JavaScript.