百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

自动化测试时,遇到验证码问题怎么办?

bigegpt 2024-09-27 00:32 3 浏览

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 Youngtitle>
head>
<body>
 br>
<h1> Test h1>
 <img src="http://csujwc.its.csu.edu.cn/sys/ValidateCode.aspx?t=1">
 br>
body>
html>

要识别验证码,首先得取得验证码,这两款采取的是页面元素部分截图的方式,首先是获取整个页面的截图

然后找到页面元素坐标进行截取

/**
     * This method for screen shot element
     * 
     * @param driver
     * @param element
     * @param path
     * @throws InterruptedException
     */
    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();
        }
    }

截取完元素,就可以调用Tesseract-OCR生成text

// use Tesseract to get strings
        Runtime 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
     * 
     * @param filePath
     */
    public static void readTextFile(String filePath) {
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(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();
        }
    }

整体代码如下:

package com.dbyl.tests;
 
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.dbyl.libarary.utils.DriverFactory;

public class TesseractTest {

     public static void main(String[] args) throws IOException,
             InterruptedException {
 
        WebDriver driver = DriverFactory.getChromeDriver();
         driver.get("file:///C:/Users/validation.html");
        driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
        WebElement element = driver.findElement(By.xpath("//img"));

        // take screen shot for element
         screenShotForElement(driver, element, "D:\\Tesseract-OCR\\test.png");
 
        driver.quit();
        
         // use Tesseract to get strings
        Runtime rt = Runtime.getRuntime();
        rt.exec("cmd.exe /C  tesseract.exe D:\\Tesseract-OCR\\test.png  D:\\Tesseract-OCR\\test -1 ");
 
         Thread.sleep(1000);
         // Read text
        readTextFile("D:\\Tesseract-OCR\\test.txt");
     }
 
    /**
     * This method for read TXT file
     * 
     * @param filePath
      */
     public static void readTextFile(String filePath) {
        try {
            String encoding = "GBK";
            File file = new File(filePath);
             if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考虑到编码格式
                 BufferedReader bufferedReader = new BufferedReader(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();
         }
     }

     /**
     * This method for screen shot element
      * 
      * @param driver
      * @param element
      * @param path
      * @throws InterruptedException
      */
     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();
         }
     }
 
 }

相关推荐

有些人能留在你的心里,但不能留在你生活里。

有时候,你必须要明白,有些人能留在你的心里,但不能留在你生活里。Sometimes,youhavetorealize,Somepeoplecanstayinyourheart,...

Python学不会来打我(34)python函数爬取百度图片_附源码

随着人工智能和大数据的发展,图像数据的获取变得越来越重要。作为Python初学者,掌握如何从网页中抓取图片并保存到本地是一项非常实用的技能。本文将手把手教你使用Python函数编写一个简单的百度图片...

软网推荐:图像变变变 一“软”见分晓

当我们仅需要改变一些图片的分辨率、裁减尺寸、添加水印、标注文本、更改图片颜色,或将一种图片转换为另一种格式时,总比较讨厌使用一些大型的图像处理软件,尤其是当尚未安装此类软件时,更是如此。实际上,只需一...

首款WP8.1图片搜索应用,搜照片得资料

首款WP8.1图片搜索应用,搜照片得资料出处:IT之家原创(天际)2014-11-1114:32:15评论WP之家报道,《反向图片搜索》(ReverseImageSearch)是Window...

分享一组美图(图片来自头条)(头条美女头像)

...

盗墓笔记电视剧精美海报 盗墓笔记电视剧全集高清种子下载

出身“老九门”世家的吴邪,因身为考古学家的父母在某次保护国家文物行动时被国外盗墓团伙杀害,吴家为保护吴邪安全将他送去德国读书,因而吴邪对“考古”事业有着与生俱来的兴趣。在一次护宝过程中他偶然获得一张...

微软调整Win11 24H2装机策略:6月起36款预装应用改为完整版

IT之家7月16日消息,微软公司今天(7月16日)发布公告,表示自今年6月更新开始,已默认更新Windows1124H2和WindowsServer2025系统中预装...

谷歌手把手教你成为谣言终结者 | 域外

刺猬公社出品,必属原创,严禁转载。合作事宜,请联系微信号:yunlugongby贾宸琰编译、整理11月23日,由谷歌新闻实验室(GoogleNewsLab)联合Bellingcat、DigD...

NAS 部署网盘资源搜索神器:全网资源一键搜,免费看剧听歌超爽!

还在为找不到想看的电影、电视剧、音乐而烦恼?还在各个网盘之间来回切换,浪费大量时间?今天就教你如何在NAS上部署aipan-netdisk-search,一款强大的网盘资源搜索神器,让你全网资源...

使用 Docker Compose 简化 INFINI Console 与 Easysearch 环境搭建

前言回顾在上一篇文章《搭建持久化的INFINIConsole与Easysearch容器环境》中,我们详细介绍了如何使用基础的dockerrun命令,手动启动和配置INFINICon...

为庆祝杜特尔特到访,这个国家宣布全国放假?

(观察者网讯)近日,一篇流传甚广的脸书推文称,为庆祝杜特尔特去年访问印度,印度宣布全国放假,并举办了街头集会以示欢迎。菲媒对此做出澄清,这则消息其实是“假新闻”。据《菲律宾世界日报》2日报道,该贴子...

一课译词:毛骨悚然(毛骨悚然的意思是?)

PhotobyMoosePhotosfromPexels“毛骨悚然”,汉语成语,意思是毛发竖起,脊梁骨发冷;形容恐惧惊骇的样子(withone'shairstandingonend...

Bing Overtakes Google in China&#39;s PC Search Market, Fueled by AI and Microsoft Ecosystem

ScreenshotofBingChinahomepageTMTPOST--Inastunningturnintheglobalsearchenginerace,Mic...

找图不求人!6个以图搜图的识图网站推荐

【本文由小黑盒作者@crystalz于03月08日发布,转载请标明出处!】前言以图搜图,专业说法叫“反向图片搜索引擎”,是专门用来搜索相似图片、原始图片或图片来源的方法。常用来寻找现有图片的原始发布出...

浏览器功能和“油管”有什么关联?为什么要下载

现在有没有一款插件可以实现全部的功能,同时占用又小呢,主题主要是网站的一个外观,而且插件则主要是实现wordpress网站的一些功能,它不仅仅可以定制网站的外观,还可以实现很多插件的功能,搭载chro...