C# .NET Proxy Setup for Web Scraping: HttpClient, Rotating Proxies, and Residential
C# .NET Proxy Setup for Web Scraping: HttpClient, Rotating Proxies, and Residential
Web scraping at scale requires robust proxy management to avoid IP bans and maintain performance. In this guide, we'll explore setting up proxies using HttpClient in C#, including rotating proxies and using residential proxies. We'll also compare the approach with Python for large-scale crawls.
Setting Up HttpClient with Proxies
To use a proxy with HttpClient, you can set the Proxy property of HttpClientHandler. Here’s how to do it:
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler
{
Proxy = new WebProxy("http://your-proxy-url:port"),
UseProxy = true,
};
var client = new HttpClient(handler);
For authenticated proxies, you can pass credentials using the Credentials property of WebProxy:
var proxy = new WebProxy("http://your-proxy-url:port")
{
Credentials = new NetworkCredential("username", "password")
};
handler.Proxy = proxy;
Rotating Proxies with DelegatingHandler
To rotate proxies, you can create a custom DelegatingHandler that selects a proxy from a list:
public class ProxyRotator : DelegatingHandler
{
private readonly List _proxies;
private int _currentIndex = 0;
public ProxyRotator(List proxies)
{
_proxies = proxies;
}
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var proxyUrl = GetNextProxy();
var handler = new HttpClientHandler
{
Proxy = new WebProxy(proxyUrl),
UseProxy = true,
};
var client = new HttpClient(handler);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
private string GetNextProxy()
{
lock (_proxies)
{
_currentIndex = (_currentIndex + 1) % _proxies.Count;
return _proxies[_currentIndex];
}
}
}
To use this handler with HttpClient:
var proxies = new List { "http://proxy1:port", "http://proxy2:port" };
var proxyRotator = new ProxyRotator(proxies);
var client = new HttpClient(proxyRotator);
Residential Proxies
Residential proxies are IP addresses from real users, which can help avoid detection by web scrapers. Providers like Bright Data and SmartProxy offer residential proxies with high reliability.
For example, the endpoint format for Bright Data is:
http://username:[email protected]/proxy-ip:port
Replace username, password, and proxy-ip with your credentials and proxy IP provided by Bright Data.
Concurrent Requests with Rate Limiting
To manage concurrent requests and avoid overwhelming the target servers, use SemaphoreSlim for rate limiting:
var semaphore = new SemaphoreSlim(10); // limit to 10 concurrent requests
await Task.WhenAll(proxies.Select(async proxy =>
{
await semaphore.WaitAsync();
try
{
var response = await client.GetAsync("http://example.com", HttpCompletionOption.ResponseHeadersRead);
// process the response
}
finally
{
semaphore.Release();
}
}));
Parsing HTML with HtmlAgilityPack
For parsing HTML responses, you can use libraries like HtmlAgilityPack:
var html = await response.Content.ReadAsStringAsync();
var doc = new HtmlDocument();
doc.LoadHtml(html);
foreach (var node in doc.DocumentNode.SelectNodes("//a[@href]"))
{
Console.WriteLine(node.GetAttributeValue("href", string.Empty));
}
Comparison to Python Scraping
C#'s type safety and compiled performance offer advantages for large-scale crawls. While Python's simplicity and extensive libraries make it popular, C# can handle higher loads and is more efficient in CPU-bound tasks.
For example, the equivalent Python code using requests and BeautifulSoup:
import requests
from bs4 import BeautifulSoup
response = requests.get("http://example.com")
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
While both languages are powerful, C# can be more suitable for high-performance applications.
Conclusion
Setting up proxies in C# using HttpClient and custom handlers allows for efficient web scraping. By rotating proxies, using residential services like Bright Data, managing concurrency with rate limiting, and parsing HTML effectively, you can build robust scrapers that scale well.
If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download
Free proxies break. ProxyForge doesn't.
The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.
Download ProxyForge free →