- 环境准备
在开始之前,请确保你的项目中引用了以下 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);
}
}
}
标签:string,C#,验证码,public,var,new,识别,response From: https://www.cnblogs.com/ocr1/p/18489188