Webdriver配合Tesseract-OCR 自动识别简单的验证码
上一篇 /
下一篇 2015-11-18 17:15:27
/ 个人分类:相关工具
验证码: 如下,在进行自动化测试,遇到验证码的问题,一般有两种方式
1.找开发去掉验证码或者使用万能验证码
2.使用OCR自动识别
使用OCR自动化识别,一般识别率不是太高,处理一般简单验证码还是没问题
这里使用的是Tesseract-OCR,下载地址:https://github.com/A9T9/Free-Ocr-Windows-Desktop/releases
怎么使用呢?
进入安装后的目录:
tesseract.exe test.png test -1
准备一份网页,上面使用该验证码
<html><head><title>Table test by Young</title></head><body></br><h1>Test</h1><imgsrc="http://csujwc.its.csu.edu.cn/sys/ValidateCode.aspx?t=1"></br></body></html>
要识别验证码,首先得取得验证码,这两款采取对 页面元素部分截图的方式,首先获取整个页面的截图
然后找到页面元素坐标进行截取
/*** This method for screen shot element
*
*@paramdriver
*@paramelement
*@parampath
*@throwsInterruptedException*/publicstaticvoidscreenShotForElement(WebDriver driver,
WebElement element, String path)throwsInterruptedException {
File scrFile=((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);try{
Point p=element.getLocation();intwidth =element.getSize().getWidth();intheight =element.getSize().getHeight();
Rectangle rect=newRectangle(width, height);
BufferedImage img=ImageIO.read(scrFile);
BufferedImage dest=img.getSubimage(p.getX(), p.getY(),
rect.width, rect.height);
ImageIO.write(dest,"png", scrFile);
Thread.sleep(1000);
FileUtils.copyFile(scrFile,newFile(path));
}catch(IOException e) {
e.printStackTrace();
}
}
截取完元素,就可以调用Tesseract-OCR生成text
//use Tesseract to get stringsRuntime rt =Runtime.getRuntime();
rt.exec("cmd.exe /C tesseract.exe D:\\Tesseract-OCR\\test.png D:\\Tesseract-OCR\\test -1 ");
接下来通过java读取txt
/*** This method for read TXT file
*
*@paramfilePath*/publicstaticvoidreadTextFile(String filePath) {try{
String encoding= "GBK";
File file=newFile(filePath);if(file.isFile() && file.exists()) {//判断文件是否存在InputStreamReader read =newInputStreamReader(newFileInputStream(file), encoding);//考虑到编码格式BufferedReader bufferedReader =newBufferedReader(read);
String lineTxt=null;while((lineTxt = bufferedReader.readLine()) !=null) {
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
整体代码如下:
View Code
相关阅读:
- web登录用户名/密码/验证码测试设计整理 (penguin04, 2011-2-15)
- 关于登录时的验证码和浏览器提示是否保存密码问题 (fanxing, 2012-9-26)
- 【转】自动化测试中的验证码处理方法小总结 (sushe2009, 2013-11-26)
- 利用QTP TextUtil对象获取图片验证码 (ChinaTNT, 2013-12-07)
- 自动化测试中的验证码处理方法小总结 (ftdtest, 2013-12-27)
- RFS连接SSH (testing200, 2015-3-13)
- QTP验证码问题 (arron310, 2015-3-23)
- Python识别网站验证码 (593743227, 2015-6-04)
- 关于QTP验证码处理方法 (yiucin, 2015-6-09)
- 关于“验证码” (fangbaobao, 2015-10-19)
收藏
举报
TAG:
验证码