热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

e2e自动化集成测试架构实例WebStormNode.jsMochaWebDriverIOSeleniumStepbystep(二)图片验证码的识别

上一篇文章讲了“e2e自动化集成测试架构京东商品搜索实例WebStormNode.jsMochaWebDriverIOSeleniumStepbystep一京东商

   上一篇文章讲了“e2e 自动化集成测试 架构 京东 商品搜索 实例 WebStorm Node.js Mocha WebDriverIO Selenium Step by step 一 京东 商品搜索”

       关于图片验证码的识别, 有多种方法, 之前有在Google, baidu上找了非常多的文章, 有非常多的方法去实现 ,但我学得使用 Google赞助的tesseract 工具,是比较不错的选择。tesseract是一个exe,  其实本文章实际上与Node.js已经没有太大的关系。因为我们要做的是如果调用这个exe.

保存验证码图片

WebdriverIo, 提供了一个接口为 saveScreenshot 就是可以保证当前页面的屏幕截图。 如下:

首先是打开一个新的窗口, captchaUrl,就是图片验证码的url地址, 如JD的是 https://authcode.jd.com/verify/image?a=1&acid=72c69aa3-7ffc-4934-b8cc-199750307af6&uid=72c69aa3-7ffc-4934-b8cc-199750307af6&yys=1413969656908%22, 放在IE中, F5,不停的刷新,你会发现,他在不停的变化。

就是保存屏幕截图。将图片存放在本地, Node.js 支持调用本地的exe, 请参考 http://nodejs.org/api/process.html 实际上就是执行CMD命令。tesseract 执行如 CMD > tesseract z:\snapshot.pgn result  执行后会在当前目录生成一个txt文件,内容就是识别后的文本。

但是在此, 为了提高识别的概率, 我会先将图片灰度化,然后再生成一张黑白图片, 最后给tesseract 支识别, 使用Node.js会比较麻烦, 所以我使用的.net c#实现, 然后做成一个服务 API, 然后,让Node.js去调用。

C#的内容如下:

[RoutePrefix("api/CaptchaDecoder")]
public class CaptchaDecoderController : ApiController
{
ILog log = LogManager.GetLogger("AppLog");

TesseractService _tesseract;
public CaptchaDecoderController()
{
log4net.Config.DOMConfigurator.Configure();
_tesseract = new TesseractService();
}

public CaptchaDecoderController(TesseractService tesseract)
{
_tesseract = tesseract;
}

[HttpPost]
public ServicePostResponse CaptchaDecoder(ServicePostRequest request)
{
var respOnse= new ServicePostResponse();
try
{
if(request == null)
{
throw new Exception("request is null");
}

if (string.IsNullOrEmpty(request.ExtraData.SystemId))
{
throw new Exception("request.ExtraData.SystemId is null or empty");
}

if (string.IsNullOrEmpty(request.ExtraData.FilePath))
{
throw new Exception("request.ExtraData.FilePath is null or empty");
}

var filePath = request.ExtraData.FilePath;
if (!File.Exists(filePath))
{
throw new Exception("File:" + request.ExtraData.FilePath + " doesn't exist");
}
using (Bitmap sourceBmp = new Bitmap(filePath))
{

GetGrayBitmap(sourceBmp);

GetBackWhiteBitmapNew(sourceBmp);

Bitmap bmp = ClearNoise(sourceBmp, 3);

bmp.Save(filePath + "_new.jpg");


fnOCR(@_tesseract.exePath, @filePath + "_new.jpg " + filePath + "_result nobatch digits");

if (File.Exists(filePath + "_result.txt"))
{
using (StreamReader file = File.OpenText(filePath + "_result.txt"))
{
response.ExtraData = file.ReadLine();
file.Close();
}

}
else
{
throw new Exception("generate the result fail");
}

bmp.Dispose();
sourceBmp.Dispose();
}



response.IsSuccess = true;
response.Total = 1;

}
catch (Exception ex)
{
log.Error(ex);
response.Errors = ex.Message;
response.IsSuccess = false;
response.Total = 0;
}
finally
{

}

return response;
}

private string GetCurrentSeqValue()
{
return System.DateTime.Now.Month.ToString("00");
}

private void GetGrayBitmap(Bitmap bmp)
{

for (int i = 0; i {
for (int j = 0; j {
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//利用公式计算灰度值
int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
Color newColor = Color.FromArgb(gray, gray, gray);
bmp.SetPixel(i, j, newColor);
}
}
}

private void GetBackWhiteBitmap(Bitmap bitmap)
{

int v = ImageHelper.ComputeThresholdValue(bitmap);
ImageHelper.PBinary(bitmap, v);

}


private void GetBackWhiteBitmapNew(Bitmap bmp)
{


int average = 0;
for (int i = 0; i {
for (int j = 0; j {
Color color = bmp.GetPixel(i, j);
average += color.B;
}
}
average = (int)(average * 1.0 / (bmp.Width * bmp.Height));


}

public Bitmap ClearNoise(Bitmap bmpobj, int MaxNearPoints)
{
int dgGrayValue = ImageHelper.ComputeThresholdValue(bmpobj);

Color piexl;
Bitmap bmp = new Bitmap(bmpobj);
int nearDots = 0;
//逐点判断
for (int i = 0; i for (int j = 0; j {
piexl = bmpobj.GetPixel(i, j);
if (piexl.R <= dgGrayValue)
{
nearDots = 0;
//判断周围8个点是否全为空
if (i == 0 || i == bmpobj.Width - 1 || j == 0 || j == bmpobj.Height - 1) //边框全去掉
{
bmp.SetPixel(i, j, Color.White);
}
else
{
if (bmpobj.GetPixel(i - 1, j - 1).R if (bmpobj.GetPixel(i, j - 1).R if (bmpobj.GetPixel(i + 1, j - 1).R if (bmpobj.GetPixel(i - 1, j).R if (bmpobj.GetPixel(i + 1, j).R if (bmpobj.GetPixel(i - 1, j + 1).R if (bmpobj.GetPixel(i, j + 1).R if (bmpobj.GetPixel(i + 1, j + 1).R }

if (nearDots <= MaxNearPoints)
bmp.SetPixel(i, j, Color.White); //去掉单点 && 粗细小3邻边点
}
else //背景
bmp.SetPixel(i, j, Color.White);
}
return bmp;
}

private void fnOCR(string v_strTesseractPath, string v_Arguments)
{
using (Process process = new System.Diagnostics.Process())
{
process.StartInfo.FileName = v_strTesseractPath;
process.StartInfo.Arguments = v_Arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
}
}

}

public class TesseractService
{
public virtual string exePath { get {
return @"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe";
} }
}

上面的代码是ASP.NET WEBAPI应用。

最后,通Node.js的Http模块的功能,可以调用这个服务如下:

var http = require('http')
, fs = require('fs')


function decoderCaptchaECommerce(siteName, callback){


var requestData = {
ExtraData: {

SystemId : siteName,
FilePath : 'Z:\\snapshot.png'
}
};

var requestDataString = JSON.stringify(requestData);

var headers = {
'Content-Type': 'application/json',
'Content-Length': requestDataString.length
};

var optiOns= {
host: '127.1.1.1'
, port: 80
, path: '/api/CaptchaDecoder/CaptchaDecoder'
, method : 'POST'
, headers: headers
};

var respOnseString= '';


var req = http.request(options, function(res){

 

res.setEncoding('utf-8');
res.on('data', function(data){

responseString += data;
console.log("验证服务结果:"+responseString);

});

res.on('end', function(){
var resultObject = JSON.parse(responseString);
callback(resultObject.ExtraData);
})

});

req.on('error', function(e) {
// TODO: handle error.
});

req.write(requestDataString);
req.end();

return responseString;

};

 


推荐阅读
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 原文http:a317222029201405212739.iteye.comblog2174140引自http:www.tuicool.comarticlesaeye6rY ... [详细]
  • idea激活服务器 3月最新注册码
    idea激活服务器3月最新注册码,https:www.yht7.comidea。详细ieda激活码不妨到云海天教程 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • Linux如何安装Mongodb的详细步骤和注意事项
    本文介绍了Linux如何安装Mongodb的详细步骤和注意事项,同时介绍了Mongodb的特点和优势。Mongodb是一个开源的数据库,适用于各种规模的企业和各类应用程序。它具有灵活的数据模式和高性能的数据读写操作,能够提高企业的敏捷性和可扩展性。文章还提供了Mongodb的下载安装包地址。 ... [详细]
  • gitpod.io,云端开发调试工具。
    gitpod,一款在线开发调试工具,使用它你可以在网页上直接开发软件项目了。比如你的项目仓库在github上,你可以直接在网址的前面添加gitpod.io#,然后回车就能在网页上使 ... [详细]
  • 问题内容npmERR!code1npmERR!pathE:\WebProject\jeecgboot-vue3\node_modules\gifsiclenpmERR!com ... [详细]
  • 招聘 | 涂鸦智能招聘IoT安全人才
    招聘 | 涂鸦智能招聘IoT安全人才 ... [详细]
  • 安装vue.js需要安装什么
    web前端|Vue.jsvue.jsweb前端-Vue.js创意留言墙源码,ssh离线安装Ubuntu,爬虫抖店物流,phpitop,seo单向链接lzw《vue.js教学》ios ... [详细]
author-avatar
嘻嘻哈哈的二狗子
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有