验证码识别处理--基于python(一)

来源:互联网 发布:linux 运行rpm文件 编辑:程序博客网 时间:2024/06/03 22:34

一、在自动化测试中,遇到验证码的处理方法有以下两种:

1、找开发去掉验证码或者使用万能验证码

2、使用OCR自动识别

    这里,方法一只要和研发沟通就行。

    方法二就是使用pytesseract自动化识别,一般识别率不是太高,处理一般简单验证码还是没问题,例如下面这种验:

  代码很简单,只需要几行代码:

from pytesseract.pytesseract import image_to_stringfrom PIL import Imageimage = Image.open('../new.jpg')  #修改保存图片的路径print imagevcode = image_to_string(image)print vcode

mac系统下,需要安装依赖库(不然会报错误),在终端安装下面两条命令即可

brew install leptonica

brew install tesseract

二、但在使用python自动化测试中会遇到一个难点,验证码怎么获取,python的webdriver API没有这样接口。 解决方法:

从页面获取验证码的坐标值得,使用PIL的Image模块,截取特定的区域

思路:将web节目截图保存-->定位到验证码坐标-->从截图中再进行验证码位置的截图

代码如下:

from PIL import Imageimport pytesseractfrom selenium import webdriverimport timeurl='https://www.baidu.com/'driver = webdriver.Chrome(executable_path="../chromedriver") #修改自己的路径driver.maximize_window()  #将浏览器最大化driver.get(url)time.sleep(3)driver.find_element_by_xpath("//*[@id=\"u1\"]/a[7]").click()time.sleep(2)driver.find_element_by_id("TANGRAM__PSP_8__userName").send_keys("qqqq")driver.find_element_by_id("TANGRAM__PSP_8__password").send_keys("qqqq")time.sleep(5)driver.save_screenshot('../aa.png')  #截取当前网页,该网页有我们需要的验证码imgelement = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_8__verifyCodeImg"]')  #定位验证码location = imgelement.location  #获取验证码x,y轴坐标size=imgelement.size  #获取验证码的长宽rangle=(int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])) #写成我们需要截取的位置坐标i=Image.open("../aa.png") #打开截图frame4=i.crop(rangle)  #使用Image的crop函数,从截图中再次截取我们需要的区域frame4.save('../frame4.jpg')qq=Image.open('../frame4.jpg')text=pytesseract.image_to_string(qq).strip() #使用image_to_string识别验证码print text


参考:

http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop

https://www.waitalone.cn/python-php-ocr.html

https://www.zhihu.com/question/22479139


0 0