python+Selenium+Pytesseract 登录时自动识别验证码

python+Selenium+Pytesseract登录时自动识别验证码

一直想试着使用python+selenium+pytesseract来做一下验证码识别。

按照网上提供的方法尝试了一下,大体的功能能实现。

(参考:https://www.jianshu.com/p/afcde49c57b7

就是想吐槽一下,这个识别的成功率真是不高。。。。

补充两点:

一、识别出来的验证码,有时候包含空格或者特殊字符。

可以使用下面的正则表达式除去

import re

code = pytesseract.image_to_string(img)
code = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", code)

二、验证码正常一次是识别不出来,需要多识别几次。

可以使用while循环 

        while True:
            # 清空验证码输入框
            d.find_element_by_css_selector('input[placeholder="请输入验证码"]').clear()
            # 找到验证码img标签,切图
            img_code = d.find_element_by_id('authCode')
            # 算出验证码的四个点,即验证码四个角的坐标地址
            left = img_code.location['x']
            top = img_code.location['y']
            right = img_code.location['x'] + img_code.size['width']
            bottom = img_code.location['y'] + img_code.size['height']
            print("验证码坐标::", left, top, right, bottom)
            # 利用python的PIL图片处理库,利用坐标,切出验证码的图
            im = Image.open('login.png')
            # 电脑设置的显示缩放比例为150%
            im = im.crop((left * 1.5, top * 1.5, right * 1.5, bottom * 1.5))
            # im = im.convert('L')  # 转换模式:L | RGB
            im = ImageEnhance.Contrast(im)  # 增强对比度
            im = im.enhance(2.0)  # 增加饱和度
            im.save('code.png')
            # 调用图片识别的函数,得到验证码
            code = self.img_to_str()
            if code:
                # 找到验证码的input,并输入验证码
                d.find_element_by_css_selector('input[placeholder="请输入验证码"]').send_keys(code)
                # 点击登录按钮
                d.find_element_by_css_selector('button[ng-click="fSub()"]').click()
                sleep(5)
                if 'index' in d.current_url:
                    print(d.current_url)
                    print("登录成功")
                    break
                else:
                    d.find_element_by_css_selector('button[class="btn btn-success"]').click()
                    print("No match!!")

 这个方法需要在输入错误的验证码后,能自动更新验证码图片。

注:文章内容主要是记录学习过程中遇到的一些问题,以及解决方法。留个记录,同时分享给有需要的人。如有不足之处,欢迎指正,谢谢! 

猜你喜欢

转载自blog.csdn.net/elsa_yxy1984/article/details/106571492