
Emma Foster
Machine Learning Engineer

Google reCAPTCHA などの CAPTCHA チャレンジは、多くのウェブサイトでボットを阻止し、コンテンツへの自動アクセスを防止するために使用されています。このようなチャレンジをプログラムで回避するには、Capsolver などの API ベースのソリューションを提供するサービスを利用できます。
このガイドでは、次の方法について説明します。
C# では、HttpClient クラスは一般的に、ウェブサイトに HTTP リクエストを送信し、レスポンスを受信するために使用されます。HtmlAgilityPack などの HTML パーサーと組み合わせることで、ウェブページからデータを抽出できます。
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"]);
}
// タスクが完了したら (ステータス: ready)、CAPTCHA トークンを返す
if (jsonResponse["status"].ToString() == "ready")
{
return jsonResponse["solution"]["gRecaptchaResponse"].ToString();
}
// 5 秒待機してから再度確認
Console.WriteLine("タスクはまだ処理中です。5 秒待機します...");
await Task.Delay(5000);
}
}
}
}
CreateTask メソッド:
/createTask エンドポイントに POST リクエストを送信します。clientKey、websiteURL、websiteKey が含まれ、タスク タイプは ReCaptchaV2TaskProxyLess に指定されています。taskId を返します。GetTaskResult メソッド:
/getTaskResult エンドポイントに POST リクエストを送信します。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"]);
}
// タスクが完了したら (ステータス: ready)、CAPTCHA トークンを返す
if (jsonResponse["status"].ToString() == "ready")
{
return jsonResponse["solution"]["gRecaptchaResponse"].ToString();
}
// 5 秒待機してから再度確認
Console.WriteLine("タスクはまだ処理中です。5 秒待機します...");
await Task.Delay(5000);
}
}
}
}
CreateTask メソッド:
/createTask エンドポイントに POST リクエストを送信します。clientKey、websiteURL、websiteKey が含まれ、タスク タイプは ReCaptchaV3TaskProxyLess に指定されています。taskId を返します。GetTaskResult メソッド:
/getTaskResult エンドポイントに POST リクエストを送信します。gRecaptchaResponse を返し、これを使用して CAPTCHA を回避できます。C# でウェブ スクレイピング ツールを使用する際は、常に以下のベストプラクティスに従ってください。
robots.txt を尊重: ウェブサイトがウェブ スクレイピングを許可しているかどうかは、robots.txt ファイルを確認して確認してください。User-Agent などのカスタムヘッダーを HTTP リクエストに追加して、ブラウザのようなリクエストをシミュレートしてください。HttpClient を使用してウェブ スクレイピングを行い、Capsolver を使用して CAPTCHA を解決することで、CAPTCHA チャレンジを使用しているウェブサイトとのやり取りを効果的に自動化できます。ウェブ スクレイピングを行う際は、常にターゲット ウェブサイトの利用規約および法的要件を遵守してください。
スクレイピングをお楽しみください!
このガイドでは、HtmlAgilityPack を使用したウェブ スクレイピングと、Capsolver を使用した reCAPTCHA チャレンジの処理方法を説明し、C# で HttpClient のみをを使用しています。
イーコマーススクリーピング中にreCAPTCHAを処理する方法を学び、コンプライアンスに準拠したワークフロー、ダイアグノスティクス、CapSolverの例、および実用的なリスク管理について学んでください。

AIを駆動するデータ抽出の仕組みについて学び、ウェブスクレイピングやCAPTCHAの解決からHTMLのクリーニング、LLMの解析、構造化されたJSONの生成までをカバーします。アンチボット回避戦略、AXEなどのセマンティック抽出フレームワーク、そしてスケーラブルなAIウェブスクレイピングパイプラインについて探求してください。

2026年のウェブオートメーション、CAPTCHAの解決、コンプライアンス、および本番環境対応のエージェントワークフロー向けの最高のAIエージェントフレームワークを比較する。
