Web scraping
Web scraping with C# HttpClient
.NET has everything a scraper needs in the box except an HTML parser, and HtmlAgilityPack fills that gap. This guide shows how to set up HttpClient correctly, parse pages with XPath and handle the errors real sites produce.
One HttpClient, configured once
The most important rule for HttpClient is to create it once and reuse it. Each instance owns a connection pool; creating one per request wastes connections and, under load, can exhaust sockets. The handler underneath decides how cookies, compression, redirects and connection limits work, so configure it deliberately.
using System.Net;
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
AllowAutoRedirect = true,
MaxConnectionsPerServer = 4,
};
var web = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
web.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) rate-survey/1.5");
web.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.8");
AutomaticDecompression makes the handler advertise and decode compressed responses, which saves bandwidth. MaxConnectionsPerServer caps parallel connections to one host, a simple politeness guard. On modern .NET, HttpClientHandler is a thin layer over SocketsHttpHandler; if you need options such as PooledConnectionLifetime (useful in long running services so DNS changes are picked up), create a SocketsHttpHandler directly, which has the same cookie and decompression properties.
Install HtmlAgilityPack
dotnet new console -n RateSurvey
cd RateSurvey
dotnet add package HtmlAgilityPack
HtmlAgilityPack parses real world HTML, including unclosed tags, into a tree you query with XPath. CSS selectors are available through add on packages if you prefer them, but XPath is built in and very capable.
Parsing with XPath
using HtmlAgilityPack;
record Rate(string Currency, decimal Buy, decimal Sell);
static List<Rate> ParseRates(string html)
{
var doc = new HtmlDocument();
doc.LoadHtml(html);
var rows = doc.DocumentNode.SelectNodes("//table[@id='rates']//tr[td]");
var list = new List<Rate>();
if (rows is null) return list;
foreach (var tr in rows)
{
var cells = tr.SelectNodes("./td");
if (cells is null || cells.Count < 3) continue;
string Cell(int i) => HtmlEntity.DeEntitize(cells[i].InnerText).Trim();
if (decimal.TryParse(Cell(1), System.Globalization.NumberStyles.Number,
System.Globalization.CultureInfo.InvariantCulture, out var buy) &&
decimal.TryParse(Cell(2), System.Globalization.NumberStyles.Number,
System.Globalization.CultureInfo.InvariantCulture, out var sell))
list.Add(new Rate(Cell(0), buy, sell));
}
return list;
}
Two HtmlAgilityPack habits matter. SelectNodes returns null, not an empty collection, when nothing matches, so check before looping. And InnerText keeps HTML entities such as & encoded; HtmlEntity.DeEntitize decodes them. Parsing numbers with the invariant culture avoids surprises when the scraper runs on a machine with a different regional format.
Retries for transient errors
HttpClient does not retry by itself. A small helper handles the usual transient cases: 429 and 5xx statuses, timeouts and network errors. It honors Retry-After when the server sends one.
static async Task<string?> FetchWithRetry(HttpClient http, string url, int attempts = 4)
{
for (var n = 0; n < attempts; n++)
{
try
{
using var res = await http.GetAsync(url);
var code = (int)res.StatusCode;
if (res.IsSuccessStatusCode) return await res.Content.ReadAsStringAsync();
if (code != 429 && code < 500) return null;
var wait = res.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(Math.Pow(2, n + 1));
await Task.Delay(wait + TimeSpan.FromMilliseconds(Random.Shared.Next(250, 900)));
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, n + 1)));
}
}
return null;
}
A TaskCanceledException here usually means the client's timeout fired. Returning null for permanent failures such as 404 lets the caller log and move on. For larger projects, the Microsoft.Extensions.Http.Resilience or Polly libraries offer configurable policies with the same effect.
Putting it together
var pages = new[] { "https://fx.example.org/rates/today", "https://fx.example.org/rates/yesterday" };
foreach (var url in pages)
{
var html = await FetchWithRetry(web, url);
if (html is null) { Console.Error.WriteLine($"skipped {url}"); continue; }
foreach (var r in ParseRates(html))
Console.WriteLine($"{url}\t{r.Currency}\t{r.Buy}\t{r.Sell}");
await Task.Delay(TimeSpan.FromSeconds(2));
}
For many pages, run fetches with Parallel.ForEachAsync and a low MaxDegreeOfParallelism, or a SemaphoreSlim. The handler's per server connection limit adds a second guard.
Validate the output of every page, not just the status code. A rates table that suddenly parses to zero rows usually means the site changed its markup or served a different page, such as a consent screen or a block page, with status 200. Log the URL and the first few hundred characters of the HTML when that happens, and stop the run if several pages in a row come back empty. That single check catches most silent failures before they reach your database.
Cookies and challenge pages
Because the handler uses a shared CookieContainer, cookies set by the site travel with later requests automatically. That also makes it easy to add a cookie earned from a challenge. When a site behind AWS WAF returns its 405 puzzle page, solve an AntiAwsWafTaskProxyLess task and add the result to the jar:
cookieJar.Add(new Uri("https://fx.example.org/"), new Cookie("aws-waf-token", solvedValue, "/"));
The next request to the site carries it. For token CAPTCHAs in forms, such as reCAPTCHA or Turnstile, post the token with the form fields using FormUrlEncodedContent through the same client. The AWS WAF in C# guide and the Turnstile in C# guide contain complete API clients.
Character encodings
ReadAsStringAsync decodes the body using the charset from the Content-Type header and falls back to UTF-8. Older sites sometimes declare their encoding only in a meta tag, or use legacy code pages such as Windows-1252 or Shift_JIS. If you see replacement characters, read the bytes with ReadAsByteArrayAsync, let HtmlAgilityPack detect the encoding from the document (doc.Load(stream, detectEncodingFromByteOrderMarks: true) or its encoding detection helpers), and register CodePagesEncodingProvider.Instance once at startup so .NET knows the legacy code pages. It is a small amount of code that saves a lot of confusing output.
Running as a scheduled worker
For recurring jobs, host the scraper in a .NET worker service. Register the client with builder.Services.AddHttpClient("rates", ...) and configure the primary handler there; IHttpClientFactory then manages handler lifetimes for you, which solves both socket reuse and DNS refresh. A BackgroundService with a PeriodicTimer runs the scrape at a fixed interval, and the built in logging records each run's status codes and row counts. Store results in a database rather than printing them, and keep the last successful run's timestamp so a failure is noticed quickly.
Common pitfalls
- Creating HttpClient in a using block per request: leads to socket exhaustion under load. Reuse one instance, or use
IHttpClientFactoryin ASP.NET Core and worker services. - Garbled text: the response was compressed and decompression was not enabled, or the page declares a charset .NET did not detect. Enable
AutomaticDecompressionand check theContent-Typeheader. - Null reference after SelectNodes: the XPath matched nothing. Check for
nulland log the URL. - Different HTML than the browser shows: the page builds content with JavaScript. Look for its JSON endpoint, or use a browser such as Playwright for .NET.
Common questions
Should I create a new HttpClient for every request?
No. Create one and reuse it, or use IHttpClientFactory. Many short lived instances waste connections and can exhaust sockets.
How do I keep cookies between requests in C#?
Give the handler a CookieContainer with UseCookies set to true. Every request through that client then sends and stores cookies.
Why does SelectNodes throw a NullReferenceException?
It returns null when nothing matches. Check the result for null before looping over it.
Does HttpClient decompress gzip automatically?
Only when AutomaticDecompression is set on the handler. Enable GZip, Deflate and Brotli for scraping.
Can HtmlAgilityPack use CSS selectors?
XPath is built in. CSS selector support comes from add on packages that extend HtmlAgilityPack.
Keep reading
- Solve Cloudflare Turnstile in C#Typed records and System.Text.Json produce a C# Turnstile client; Selenium for .NET writes the token into the form.
- Solve AWS WAF CAPTCHA in C#A DelegatingHandler for .NET that spots the AWS WAF puzzle, adds the aws-waf-token cookie to a CookieContainer and resends.
- XPathXPath navigates a document tree in any direction, matches on text, and handles cases where CSS selectors run out of road.
- CookieSmall values a site stores in the client, which carry sessions and the clearance proof issued after a passed challenge.