Python3 识别图片验证码的步骤

注:需要导入 PIL中的Image和ImageEnhance、pytesseract

处理思路:

1、进入登录页,使用截图功能将当前页面截图

2、定位验证码位置

3、获取验证码x,y坐标轴

4、获取验证码的长宽

5、写成自己需要的长度

6、打开截图并从截图中获取需要的区域

7、保存截图

8、打开截图

9、设置图像加强模式

10、识别验证码

11、将验证码打印出来(或在其它类中引用该结果)

源码如下:

# coding:utf-8
from selenium import webdriver
from time import sleep
import unittest
from PIL import Image
from PIL import ImageEnhance
import pytesseract
# n=10
# for n in range(10):
driver=webdriver.Firefox()
url = "被测地址"   #一般在登录首页
driver.get(url)
driver.maximize_window()
driver.save_screenshot(r"D:\\image\\aa.png")  #截取当前网页,该网页有我们需要的验证码
imgelement = driver.find_element_by_id("imagecode")  #定位验证码
location = imgelement.location  #获取验证码x,y轴坐标
size=imgelement.size  #获取验证码的长宽
coderange=(int(location['x']),int(location['y']),int(location['x']+size['width']+2),
    int(location['y']+size['height'])) #写成我们需要截取的位置坐标
i = Image.open(r"D:\\image\\aa.png") #打开截图
frame4 = i.crop(coderange)  #使用Image的crop函数,从截图中再次截取我们需要的区域
frame4.save(r"D:\\image\\aa.png")    #保存截图
i2 = Image.open(r"D:\\image\\aa.png")  #打开截图
imgry = i2.convert('L')   #图像加强,二值化,PIL中有九种不同模式。分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。L为灰度图像
sharpness = ImageEnhance.Contrast(imgry) #对比度增强
i3 = sharpness.enhance(3.0)  #3.0为图像的饱和度
i3.save("D:\\image\\image_code.png")
i4 = Image.open("D:\\image\\image_code.png")
text = pytesseract.image_to_string(i2).strip() #使用image_to_string识别验证码
print(text.replace(' ',''))   #该方法的作用为 将图片内容中的空格去除

你可能感兴趣的:(Python3)