使用selenium进行自动化测试过程中,存在网站登录的时候需要输入验证码,由于是线上环境无法关闭,故使用tesseract工具辅助识别,但是较为复杂的验证码无法识别。
一、安装tesseract工具
1. 双击安装tesseract-ocr-w64-setup-v5.0.0.20190623.exe,需要记 住安装路径, 后续会使用上,并加入到环境变量,cmd命令窗口输入tesseract -v 验证是否安装正确
下载链接:Index of /tesseract
1.cmd中执行pip install pytesseract -i https://pypi.tuna.tsinghua.edu.cn/simple (存在python虚拟环境的话需要先 进入虚拟环境,电脑安装了loadrunner,使用pip3 install pytesseract -i https://pypi.tuna.tsinghua.edu.cn/simple)
3.在python的安装目录下的Lib\site-packages中找到修改python中pytesseract依赖中修改的pytesseract.py文件中的tesseract_cmd路径为第一步中的安装路径+tesseract.exe
centos安装tesseract,目前能找到的帖子一般都是让自己下载包,用./configure形式安装,这样太复杂。
测试可以直接用yum install tesseract方式搞定。步骤如下
1. 安装opencv
直接pip install opencv-python
2. yum install tesseract
会出现很多需要安装的依赖库,如leptonica等等,敲y,就一路安装到complete。
3.安装pytesseract
直接pip install pytesseract
具体实现验证码识别代码如下(每次识别可能出现识别不对的情况,可进行循环识别调用该方法即可,直到识别正确登录成功即可break):
import time from PIL import Image import pytesseract
def get_code(self): screenImg = "f.png" # 浏览器页面截屏 self.dr.save_screenshot(screenImg) # 定位验证码位置及大小 location = self.dr.find_element_by_xpath('//img[@class="code-img"]').location size = self.dr.find_element_by_xpath('//img[@class="code-img"]').size rangle = (int(location['x']/0.8), int(location['y']/0.8), int(location['x']/0.8) + size['width']/0.8, int(location['y']/0.8) + size['height']/0.8,) # 我们需要截取的验证码坐标(ps:如果电脑屏幕缩放比例不是100%,需要作出对应比例变更,我电脑屏幕缩放比例是推荐的125%,。可以在电脑的显示设置里面查看) i = Image.open('f.png') # 整张网页 verifycodeimage = i.crop(rangle) # 从网页截图截取验证码区域 verifycodeimage.save('f2.png') im = Image.open('f2.png') # 验证码区域 code = pytesseract.image_to_string(im, config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789') #由于测试的网站是数字验证码,所以这里设置验证码识别范围 # 输入识别的验证码 self.dr.find_element_by_xpath('//input[@placeholder="请输入验证码"]').clear() self.dr.find_element_by_xpath('//input[@placeholder="请输入验证码"]').send_keys(code.strip()) #输入验证码 self.dr.find_element_by_xpath('//button[@class="el-button login-btn el-button--primary el-button--large"]').click() #登录 sleep(1) time.sleep(2)