网络爬虫以及自动化测试中图形验证码识别解决思路以及方法

前言

做自动化测试的朋友都知道图形验证码在整个自动化执行过程中,很可能是阻碍推进的问题,可以采用万能验证码(开发哥哥会流出一个供自动化测试用的),如果不通过开发预留,有以下解决方案。

解决思路

1.python3自带光学字符识别模块tesserocr与pytesseract,可以识别简单验证码;
2.稍复杂不容易识别的验证码,有大神给出解决方案是:完美验证码识别系统V3.2.1.zip,使用过程中需要制作自己验证码的识别库,简单可靠;
3.python神经网络训练识别验证码。

实现代码

1.python自带pytesseract库识别简单验证码:
#!/usr/bin/env python
import pytesseract
class ShiBie():
    
    #  图形验证码xpath
    tuxing_loc = (
    "xpath", "/html/body/div[1]/div[1]/div/div/div[2]/div/form/div/div[2]/dl/dd[1]/div[5]/a/img")

    # 获取提前定义好的验证码存储路径
    shot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + ("\\screenshot\\hf_im\\screenshot.png")
    
    def huoqutuxing(self):
        element = self.findElement(self.tuxing_loc)
        left = element.location['x']
        top = element.location['y']
        right = element.location['x'] + element.size['width']
        bottom = element.location['y'] + element.size['height']
        im = Image.open(self.shot)
        im = im.crop((left, top, right, bottom))
        img = im.convert('L')  # 转换模式:L | RGB
        img = ImageEnhance.Contrast(img)  # 增强对比度
        img = img.enhance(2.0)  # 增加饱和度
        img.save(self.shot)
        code = pytesseract.image_to_string(img)
        img.close()
        print(code)
        return code.replace(' ', '')
    # 由于识别过程不一定准确,需要增加后续代码,确保输入正确
    def yzm_huoqu(self,driver):
        for i in range(5):
            if not self.is_alert(driver):
                s = self.huoqutuxing()
                self.input_tuxing(s)
                self.click_yzm_button()
                time.sleep(5)
            else:
                break
                

将以上代码封装到你自己的方法中,可以识别容易是别的验证码。

2.完美验证码识别系统:

具体参考大神csdn:https://download.csdn.net/download/crazyidea88/10178098
# coding=gbk
import urllib
import time
import string
import ctypes
from ctypes import *
# 加载dll文件
dll = ctypes.windll.LoadLibrary('WmCode.dll')
if(dll.UseUnicodeString(1,1)): #传入的文本格式
print('SetInUnicode Success:')#UseUnicodeString调用一次即可,无需重复调用,重复调用会出现系统级IO错误。
else:
print('etInUnicode Fail!')

if(dll.LoadWmFromFile('C:\Users\Administrator\Desktop\1\shibie.dat','xxx')):#使用绝对路径
    print('Loaddat Success:')#LoadWmFromFile调用一次即可,无需重复调用
    Str = create_string_buffer(20)#创建文本缓冲区
    if(dll.GetImageFromFile(C:\Users\Administrator\Desktop\1\wylt.JPG',Str)):#使用绝对路径
            print('GetVcode Success:',Str.raw.decode("gbk"))
    else:
            print('GetVcode Fail!')
else:
    print('Loaddat Fail!')
    
3.python神经网络训练识别验证码

关于神经网络训练练识别验证码网上资料很多,这里不做整理

总结

具体用那种方法因人而已,看验证码复杂程度选择,我们只是代码的搬运工,由点到面,面到体,在巨人的肩上了解更多的技术发展。

猜你喜欢

转载自www.cnblogs.com/mo-chen/p/9817832.html