In this Article
オンラインで行う操作には、さまざまな痕跡が残ります。こうした痕跡は、セキュリティ上のリスクになったり、ウェブスクレイピングの妨げになったりする場合があります。プロキシを利用すると、作業を中断させずに検出システムによる監視を回避しやすくなります。この記事では、.NET環境のC#でDataImpulseプロキシを設定する方法を紹介します。これにより、レート制限にかかったり、悪意のある第三者に情報を与えたりするリスクを抑えられます。
はじめに
まず、必要なツールが開発環境にインストールされていることを確認してください。
- Visual Studio Code(Visual Studio 2022、または.NETに対応したその他の開発環境でも構いません)
- .NET 8
- HtmlAgilityPack(このチュートリアルではバージョン1.6.11を使用します)
このチュートリアルでプロキシを使用するには、DataImpulseアカウントと用途に合ったプランが必要です。手順については、ステップバイステップガイドをご覧ください。
このチュートリアルでは、例として当社ウェブサイトの DataImpulse.comをスクレイピングします。コードは用途に合わせて簡単に調整でき、必要なソースをスクレイピングできます。データを収集するウェブサイトの利用規約に違反しないよう、必ず確認してください。
HTTPクライアントを作成する
まず、指定したプロキシサーバー経由でトラフィックをルーティングするHTTPクライアントを作成します。これは、指定したURLにリクエストを送信し、プロキシサーバー経由でレスポンスを受け取るシンプルなコンソールアプリです。以下のコードをコピーして使用できます。
using System.Net;
class HttpClientApp
{
public static void Main(string[] args)
{
DownloadPageAsync().Wait();
}
private static async Task DownloadPageAsync()
{
string page = "https://api.ipify.org/"; // Example API to get the public IP address
// Configure proxy
var proxy = new WebProxy("gw.dataimpulse.com:823")
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential("your login", "your password")
};
// Set up HTTP client handler with proxy
var httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
using (var client = new HttpClient(handler: httpClientHandler, disposeHandler: true))
{
try
{
// Send the HTTP GET request
var response = await client.GetAsync(page);
// Check if the response is successful
response.EnsureSuccessStatusCode();
// Get the content of the response
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response received: ");
Console.WriteLine(result);
Console.WriteLine("Press any key to exit.");
Console.ReadLine(); // Keep the console open to display the result
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
Console.WriteLine("Press any key to exit.");
Console.ReadLine(); // Keep the console open to display the result
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
Console.WriteLine("Press any key to exit.");
Console.ReadLine(); // Keep the console open to display the result
}
}
}
}
このアプリと以降の例を実行するには、アプリのルートディレクトリでターミナルを開き、次のコマンドを入力します。
dotnet run --project NameOfProject
出力は次のようになります。
プロキシのローテーションを実装する
プロキシサーバー経由でトラフィックをルーティングするだけでは十分ではありません。トラフィックを適切に管理するには、リクエストごとに異なるIPアドレスを使用する必要があります。そのため、次のステップでは、プロキシプールからランダムにアドレスを選択するプロキシローテーターを作成します。
using System.Net;
class ProxyRotator
{
// List of proxies to rotate through
private static List proxies = new List
{
new WebProxy("http://gw.dataimpulse.com:10000"),
new WebProxy("http://gw.dataimpulse.com:10001"),
new WebProxy("http://gw.dataimpulse.com:10002")
};
public static void Main(string[] args)
{
MakeRequestsWithRotation().Wait();
}
private static async Task MakeRequestsWithRotation()
{
// Example URLs to request
string url = "https://api.ipify.org/";
for (int i = 0; i < proxies.Count; i++)
{
// Send request using each proxy
Console.WriteLine($"Using proxy: {proxies[i].Address}");
try
{
var response = await SendRequestWithProxy(url, proxies[i]);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Request succeeded with proxy {proxies[i].Address}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"IP address from API website: {responseBody}"); // Print or process the response as needed
}
else
{
Console.WriteLine($"Request failed with proxy {proxies[i].Address}, Status Code: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception with proxy {proxies[i].Address}: {ex.Message}");
}
}
}
// Function to send request using a specific proxy
private static async Task SendRequestWithProxy(string url, WebProxy proxy)
{
HttpClientHandler handler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
using (HttpClient client = new HttpClient(handler))
{
return await client.GetAsync(url);
}
}
}
上の例では、ローテーションに使用するプロキシのリスト(この例では3個のプロキシ)を用意し、http://api.ipify.org/でローテーション後のIPアドレスを確認します。結果は次のようになります。
プロキシチェッカーを作成する
プロキシが機能していることを確認するには、プロキシチェッカーを設定します。このチェッカーはHTTPリクエストをプロキシサーバー経由で送信し、プロキシが有効かどうかを確認します。ここではdataimpulse.comを使用しますが、別のURLを指定しても構いません。
using System.Net;
class ProxyChecker
{
// Entry point renamed to avoid conflict
public static void Main(string[] args)
{
string proxyAddress = "gw.dataimpulse.com"; // Replace with your proxy address
// Replace with your proxy ports
var proxyPortStart = 10000;
var proxyPortEnd = 10100;
var tasks = new List();
for (var proxyPort = proxyPortStart; proxyPort < proxyPortEnd; proxyPort++)
{
tasks.Add(CheckProxy(proxyAddress, proxyPort));
}
Task.WaitAll(tasks.ToArray());
}
public static async Task CheckProxy(string proxyAddress, int proxyPort)
{
var proxy = new WebProxy(proxyAddress, proxyPort)
{
// Uncomment and modify if the proxy requires credentials
Credentials = new NetworkCredential("your login", "your password"),
BypassProxyOnLocal = false
};
var httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
using (var client = new HttpClient(httpClientHandler))
{
try
{
client.Timeout = TimeSpan.FromSeconds(10); // Set a timeout
var response = await client.GetAsync("https://api.ipify.org/"); // You can use any URL for testing
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Proxy is working: " + proxyAddress + ":" + proxyPort);
}
else
{
Console.WriteLine("Proxy is not working (Invalid response): " + proxyAddress + ":" + proxyPort);
}
}
catch (Exception ex)
{
Console.WriteLine("Proxy is not working (Exception): " + proxyAddress + ":" + proxyPort + " - " + ex.Message);
}
}
}
}
ここでは、ホスト名、ポート、認証情報を指定します。これらはDIダッシュボードの該当するプランのタブで確認できます。また、タイムアウトは秒単位で設定します。
得られる結果の例は次のとおりです。
データをスクレイピングする
このプロジェクトの中心となるのはウェブスクレイパーです。HTTPリクエストを送信し、DataImpulseのホームページからHTMLを取得します。
using System.Net;
using HtmlAgilityPack;
class WebScraper
{
public static void Main(string[] args)
{
Scrape().Wait();
}
private static async Task Scrape()
{
// Define the proxy details
string proxyAddress = "http://gw.dataimpulse.com:823"; // Replace with your proxy address
string proxyUsername = "your login"; // Replace with your proxy username (if needed)
string proxyPassword = "your password"; // Replace with your proxy password (if needed)
// Create a Proxy Handler
var httpClientHandler = new HttpClientHandler
{
Proxy = new WebProxy(proxyAddress)
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword)
},
UseProxy = true
};
// Create an HttpClient using the handler with the proxy
using (var client = new HttpClient(httpClientHandler))
{
// Define the target URL to scrape
string url = "https://dataimpulse.com/";
var baseUri = new Uri(url);
try
{
// Send GET request
var response = await client.GetAsync(url);
// Use the new code snippet here
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
// Load the HTML content into an HtmlDocument
HtmlDocument doc = new();
doc.LoadHtml(content);
// Use XPath to find all tags that are direct children of , , or
var nodes = doc.DocumentNode.SelectNodes("//li/a[@href] | //p/a[@href] | //td/a[@href]");
if (nodes != null)
{
foreach (var node in nodes)
{
string hrefValue = node.GetAttributeValue("href", string.Empty);
string title = node.InnerText; // This gets the text content of the tag, which is usually the title
var fullUri = new Uri(baseUri, hrefValue);
Console.WriteLine($"Title: {title}, Link: {fullUri.AbsoluteUri}");
// You can process each title and link as required
}
}
else
{
Console.WriteLine("No matching nodes found.");
}
}
else
{
Console.WriteLine($"Failed to scrape. Status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}
ウェブスクレイパーを作成するには、プロキシアドレス、認証情報、対象URLを指定します。さらに、収集するコンテンツを指定します。この例では、すべてのタイトルとリンクを取得します。レスポンスは次のようになります。
必要に応じてコードを変更し、目的のデータを取得できます。
DataImpulseを選ぶ理由
ウェブスクレイピングでは、費用を抑えるために公開プロキシを使いたくなるかもしれません。しかし、無料プロキシには、接続の失敗や速度低下、個人データの漏えいなど、多くのリスクがあります。サーバーの運営者が分からないためです。無料プロキシを避けるべき理由については、次の記事をご覧ください: 偽のIPと無料プロキシを使うべきでない理由 と 低速からセキュリティ脅威まで: 無料プロキシを避けるべき理由。そのため、信頼できるプロバイダーを利用することが重要です。DataImpulseは、悪意のある活動に関与していない、合法的に取得されたIPアドレスを提供しており、手頃な価格のプランも用意しています。たとえば、住宅用プロキシを1 GBあたり$1で購入できます。従量課金制のため、トラフィックの有効期限を心配する必要はありません。画面右上の”今すぐ試す“ボタンをクリックするか、[email protected]までご連絡ください。





