- 環境準備
在開始之前,請確保你的專案中引用了以下 NuGet 包:
Tesseract
RestSharp
在 Visual Studio 中,你可以透過 NuGet 包管理器安裝它們:
bash
Install-Package Tesseract
Install-Package RestSharp
確保你已安裝 Tesseract OCR 引擎,並將其路徑配置在系統環境變數中。
- 下載驗證碼圖片
使用 RestSharp 下載驗證碼圖片並儲存到本地:
csharp
using RestSharp;
using System.IO;
public class CaptchaDownloader
{
public static void DownloadCaptcha(string url, string savePath)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
var response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
File.WriteAllBytes(savePath, response.RawBytes);
Console.WriteLine($"驗證碼圖片已儲存為 {savePath}");
}
else
{
Console.WriteLine($"下載失敗: {response.StatusCode}");
}
}
}
3. 影像處理與 OCR 識別
使用 Tesseract 進行 OCR 識別:
csharp
更多內容聯絡1436423940
using Tesseract;
public class CaptchaRecognizer
{
public static string RecognizeCaptcha(string imagePath)
{
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(imagePath))
{
var result = engine.Process(img);
Console.WriteLine($"識別結果: {result.GetText().Trim()}");
return result.GetText().Trim();
}
}
}
}
4. 自動化登入
使用 RestSharp 傳送 POST 請求,模擬登入操作:
csharp
public class Login
{
public static void LoginToWebsite(string username, string password, string captcha)
{
var client = new RestClient("https://captcha7.scrape.center/login");
var request = new RestRequest(Method.POST);
request.AddJsonBody(new { username, password, captcha });
var response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Console.WriteLine("登入成功");
}
else
{
Console.WriteLine($"登入失敗: {response.StatusCode}");
}
}
}
5. 主程式
整合上述程式碼,建立主程式:
csharp
class Program
{
static void Main(string[] args)
{
string captchaUrl = "https://captcha7.scrape.center/captcha.png";
string captchaPath = "captcha.png";
// 下載驗證碼圖片
CaptchaDownloader.DownloadCaptcha(captchaUrl, captchaPath);
// 識別驗證碼
string captchaText = CaptchaRecognizer.RecognizeCaptcha(captchaPath);
// 模擬登入
if (!string.IsNullOrEmpty(captchaText))
{
Login.LoginToWebsite("admin", "admin", captchaText);
}
}
}