有个系统登录的时候需要验证码,而“敬业”的程序员哥哥不肯给我留个万能验证码,更不肯留个后门。所以只能自食其力了。
用到的工具主要是tesseract-ocr(图像识别工具)
1、首先是安装,可以网上找安装教程。
2、其次是写个批处理文件(前面是图片地址,后边是转换后的txt文件地址)
3、再在目录下放一个验证码图片,运行批处理文件,看下是否生成了对应的txt文件。有生成的话证明读取图片内容没有问题。
4、再代码中使用如下:
a、首先截取验证码(传入验证码元素以及存放的截图地址):
代码如下:
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenShot {
public static void screenShotForElement(WebDriver driver,
WebElement element, String path) throws InterruptedException {
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
Point p = element.getLocation();
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
Rectangle rect = new Rectangle(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, new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
b、截取验证码:
public static void loginCode(WebDriver driver) throws InterruptedException {
WebElement element = driver.findElement(By.xpath("//*[@id='image1']"));
ScreenShot.screenShotForElement(driver, element, "F:\\wumiaohong\\workspace2\\小学数学解题大赛\\image\\vercode.jpg");
}
c、读取txt中的验证码:
public static String ReadTXT(){
File file = new File("F:\\wumiaohong\\workspace2\\小学数学解题大赛\\image\\vercode.txt");
String result = "";
try{
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
while((s = br.readLine())!=null){
result = result + "\n" +s;
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
d、case中使用:
转换的代码就是批处理文件中的代码,也可以直接调用批处理文件,但是我使用中一直不成功,所以直接用了代码。
此外,图像识别正确率为90%,如果干扰比较大的话,读取出来的文字是不正确的。所以为了测试方便和正确,最好让开发GG留个后门,上正式线再去掉就好了。
领取专属 10元无门槛券
私享最新 技术干货