
Anh Tuan
Data Science Expert

网站通常会使用 CAPTCHA 挑战(例如 Google reCAPTCHA)来阻止机器人并防止自动访问其内容。为了以编程方式绕过这些挑战,您可以使用像 Capsolver 这样的服务,它们提供基于 API 的解决方案来解决这些 CAPTCHA。
在本指南中,我们将向您展示如何:
在 C# 中,HttpClient 类通常用于发送 HTTP 请求并接收来自网站的响应。您可以将其与 HTML 解析器(如 HtmlAgilityPack)结合使用来从网页中提取数据。
Install-Package HtmlAgilityPack
Install-Package Newtonsoft.Json
让我们使用 HttpClient 和 HtmlAgilityPack 从 Quotes to Scrape 网站抓取报价。
using System;
using System.Net.Http;
using System.Threading.Tasks;
using HtmlAgilityPack;
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
string url = "http://quotes.toscrape.com/";
// 向页面发送 GET 请求
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
// 使用 HtmlAgilityPack 解析页面内容
string pageContent = await response.Content.ReadAsStringAsync();
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(pageContent);
// 查找页面上的所有报价
var quotes = htmlDoc.DocumentNode.SelectNodes("//span[@class='text']");
// 打印每个报价
foreach (var quote in quotes)
{
Console.WriteLine(quote.InnerText);
}
}
else
{
Console.WriteLine($"无法检索页面。状态码:{response.StatusCode}");
}
}
}
text 的元素来提取报价。当网站使用 reCAPTCHA v3 和 reCaptcha v2 进行安全保护时,您可以使用 Capsolver API 来解决 CAPTCHA。以下是将 Capsolver 与 HttpClient 集成以解决 reCAPTCHA 挑战的方法。
Install-Package Newtonsoft.Json
在本节中,我们将演示 如何使用 Capsolver API 和 HttpClient 解决 reCAPTCHA v2 挑战。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
private static readonly string apiUrl = "https://api.capsolver.com";
private static readonly string clientKey = "YOUR_API_KEY"; // 替换为您的 Capsolver API 密钥
static async Task Main(string[] args)
{
try
{
// 步骤 1:创建用于解决 reCAPTCHA v3 的任务
string taskId = await CreateTask();
Console.WriteLine("任务 ID: " + taskId);
// 步骤 2:检索任务的结果
string taskResult = await GetTaskResult(taskId);
Console.WriteLine("任务结果(CAPTCHA 令牌): " + taskResult);
}
catch (Exception ex)
{
Console.WriteLine("错误: " + ex.Message);
}
}
// 创建新 CAPTCHA 解决任务的方法
private static async Task<string> CreateTask()
{
using (HttpClient client = new HttpClient())
{
// 请求有效负载
var requestBody = new
{
clientKey = clientKey,
task = new
{
type = "ReCaptchaV2TaskProxyLess", // 用于无代理 reCAPTCHA v3 的任务类型
websiteURL = "", // 要为其解决 CAPTCHA 的网站 URL
websiteKey = "" // reCAPTCHA 站点密钥
}
};
// 发送创建任务的请求
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"{apiUrl}/createTask", content);
string responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception("无法创建任务:" + responseContent);
}
JObject jsonResponse = JObject.Parse(responseContent);
if (jsonResponse["errorId"].ToString() != "0")
{
throw new Exception("创建任务出错:" + jsonResponse["errorDescription"]);
}
// 返回将在下一步中使用的任务 ID
return jsonResponse["taskId"].ToString();
}
}
// 检索 CAPTCHA 解决任务结果的方法
private static async Task<string> GetTaskResult(string taskId)
{
using (HttpClient client = new HttpClient())
{
// 请求有效负载
var requestBody = new
{
clientKey = clientKey,
taskId = taskId
};
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
// 每 5 秒轮询一次任务结果
while (true)
{
HttpResponseMessage response = await client.PostAsync($"{apiUrl}/getTaskResult", content);
string responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception("无法获取任务结果:" + responseContent);
}
JObject jsonResponse = JObject.Parse(responseContent);
if (jsonResponse["errorId"].ToString() != "0")
{
throw new Exception("获取任务结果出错:" + jsonResponse["errorDescription"]);
}
// 如果任务已准备就绪,则返回 CAPTCHA 令牌
if (jsonResponse["status"].ToString() == "ready")
{
return jsonResponse["solution"]["gRecaptchaResponse"].ToString();
}
// 在再次检查之前等待 5 秒
Console.WriteLine("任务仍在处理中,等待 5 秒...");
await Task.Delay(5000);
}
}
}
}
CreateTask 方法:
/createTask 端点发送 POST 请求以创建一个用于解决 reCAPTCHA v2 挑战的新任务。clientKey、websiteURL、websiteKey,并指定任务类型为 ReCaptchaV2TaskProxyLess。taskId,该 taskId 将用于检索任务结果。GetTaskResult 方法:
/getTaskResult 端点发送 POST 请求以检查先前创建的任务的结果。status: ready)。gRecaptchaResponse,该响应可用于绕过 CAPTCHA。在本节中,我们将演示 如何使用 Capsolver API 和 HttpClient 解决 reCAPTCHA v3 挑战。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
private static readonly string apiUrl = "https://api.capsolver.com";
private static readonly string clientKey = "YOUR_API_KEY"; // 替换为您的 Capsolver API 密钥
static async Task Main(string[] args)
{
try
{
// 步骤 1:创建用于解决 reCAPTCHA v3 的任务
string taskId = await CreateTask();
Console.WriteLine("任务 ID: " + taskId);
// 步骤 2:检索任务的结果
string taskResult = await GetTaskResult(taskId);
Console.WriteLine("任务结果(CAPTCHA 令牌): " + taskResult);
}
catch (Exception ex)
{
Console.WriteLine("错误: " + ex.Message);
}
}
// 创建新 CAPTCHA 解决任务的方法
private static async Task<string> CreateTask()
{
using (HttpClient client = new HttpClient())
{
// 请求有效负载
var requestBody = new
{
clientKey = clientKey,
task = new
{
type = "ReCaptchaV3TaskProxyLess", // 用于无代理 reCAPTCHA v3 的任务类型
websiteURL = "", // 要为其解决 CAPTCHA 的网站 URL
websiteKey = "" // reCAPTCHA 站点密钥
}
};
// 发送创建任务的请求
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"{apiUrl}/createTask", content);
string responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception("无法创建任务:" + responseContent);
}
JObject jsonResponse = JObject.Parse(responseContent);
if (jsonResponse["errorId"].ToString() != "0")
{
throw new Exception("创建任务出错:" + jsonResponse["errorDescription"]);
}
// 返回将在下一步中使用的任务 ID
return jsonResponse["taskId"].ToString();
}
}
// 检索 CAPTCHA 解决任务结果的方法
private static async Task<string> GetTaskResult(string taskId)
{
using (HttpClient client = new HttpClient())
{
// 请求有效负载
var requestBody = new
{
clientKey = clientKey,
taskId = taskId
};
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
// 每 5 秒轮询一次任务结果
while (true)
{
HttpResponseMessage response = await client.PostAsync($"{apiUrl}/getTaskResult", content);
string responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception("无法获取任务结果:" + responseContent);
}
JObject jsonResponse = JObject.Parse(responseContent);
if (jsonResponse["errorId"].ToString() != "0")
{
throw new Exception("获取任务结果出错:" + jsonResponse["errorDescription"]);
}
// 如果任务已准备就绪,则返回 CAPTCHA 令牌
if (jsonResponse["status"].ToString() == "ready")
{
return jsonResponse["solution"]["gRecaptchaResponse"].ToString();
}
// 在再次检查之前等待 5 秒
Console.WriteLine("任务仍在处理中,等待 5 秒...");
await Task.Delay(5000);
}
}
}
}
CreateTask 方法:
/createTask 端点发送 POST 请求以创建一个用于解决 reCAPTCHA v3 挑战的新任务。clientKey、websiteURL、websiteKey,并指定任务类型为 ReCaptchaV3TaskProxyLess。taskId,该 taskId 将用于检索任务结果。GetTaskResult 方法:
/getTaskResult 端点发送 POST 请求以检查先前创建的任务的结果。status: ready)。gRecaptchaResponse,该响应可用于绕过 CAPTCHA。在 C# 中使用网页抓取工具时,请始终遵循以下最佳实践:
robots.txt: 通过检查 robots.txt 文件,确保网站允许网页抓取。User-Agent)来模拟浏览器式请求。通过使用 HttpClient 进行网页抓取和 Capsolver 解决 CAPTCHA,您可以有效地自动执行与使用 CAPTCHA 挑战的网站的交互。始终确保您的网页抓取活动符合目标网站的服务条款和法律要求。
祝您抓取愉快!
本指南集成了使用 HtmlAgilityPack 的网页抓取,并演示了如何使用 Capsolver 处理 reCAPTCHA 挑战,仅使用 C# 中的 HttpClient。
比较2026年最佳AI代理框架在网页自动化、验证码解决、合规性和生产就绪代理工作流程中的表现。
