pytesseract+mechanize识别验证码自动登陆

发布时间:2018-07-11 21:40:58编辑:Run阅读(6335)

    pytesseract+mechanize识别验证码自动登陆

    需要的模块

    安装Pillow,Python平台的图像处理标准库

    pip install pillow


    安装pytesseract,文字识别库

    pip install pytesseract


    安装tesseract-ocr,识别引擎

    windows:

    https://digi.bib.uni-mannheim.de/tesseract/

    下载

    tesseract-ocr-setup-3.05.02 或者 tesseract-ocr-setup-4.0.0-alpha


    linux:

    github上面下载对应版本

    https://github.com/tesseract-ocr/tesseract


    遇到问题及解决:

    pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path


    解决方法:(我是win环境)

    找到tesseract-ocr安装目录,复制路径如:  C:\Program Files (x86)\Tesseract-OCR\tesseract.exe

    找到pytesseract.py文件,修改tesseract_cmd的路径,如下:


    blob.png


    安装mechanize,是一个 Python 模块,用于模拟浏览器

    pip install mechanize



    程序思路:

    1.首先打开目标网站,找到验证码的图片地址,并下载下来

    2.利用pytesseract识别出图片中的验证码(想要识别率高,可训练)并返回一个str结果

    3.使用mechanize模拟登陆,找到form表单,提交账号,密码,验证码等信息

    4.登陆成功,然后爬取想要的内容


    需要爬取的网站

    blob.png


    完整代码:

    #!/usr/bin/env python
    # coding: utf-8
    import mechanize
    import sys
    from bs4 import BeautifulSoup
    from PIL import Image
    import pytesseract
    
    # py2.7声明使用utf-8编码
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    
    class Item(object):  # 定义一个Item类,爬取的字段类
        landing_name = None  # 登陆账号
        landing_time = None  # 登陆时间
    
    
    class SimulateLogin(object):
        def __init__(self, url, username, password, img_url):
            # 初始化
            self.url = url            # 模拟登陆后台地址
            self.img_url = img_url    # 验证码下载地址
            self.username = username  # 账号
            self.password = password  # 密码
            self.bs4_filter()
    
        def mechanize_setting(self):
            # 打开浏览器
            br = mechanize.Browser()
    
            # 设置浏览器
            br.set_handle_equiv(True)
            br.set_handle_redirect(True)
            br.set_handle_referer(True)
            br.set_handle_robots(False)
            br.set_handle_gzip(False)
    
            # Follows refresh 0 but not hangs on refresh > 0
            br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
    
            # 设置user-agent
            br.addheaders = [('User-agent','Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615
             Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
            return br
    
        def login(self):  # 模拟登陆函数
            br = self.mechanize_setting()
            self.img_download(br)
            vf_code = self.img_to_str()
            br.open(self.url)
            # 打印form表单需要提交的信息
            for form in br.forms():
                print(form)
            # 注意:
            # post 指的是请求方式
            # TextControl(username=)对应的是账号
            # PasswordControl(password=)对应的是密码
            # TextControl(captcha=)对应的是验证码
            try:
                br.select_form(method='post')
                br.form['username'] = self.username
                br.form['password'] = self.password
                br.form['captcha'] = vf_code
                br.submit()
            except Exception as e:
                print('form表信息填写错误:%s' % e)
            else:
                ret = br.response().read()
                return ret
    
        def img_download(self, br):  # 下载验证码
            img = br.open(self.img_url)
            with open('1.jpg', 'wb') as f:
                f.write(img.read())
    
        def bs4_filter(self):  # 登陆成功后,爬取内容
            items = []
            ret = self.login()
            # 利用bs4 获取登陆成功后的一些信息
            soup = BeautifulSoup(ret, 'lxml')
            print(soup)  # 这里的返回值已经提示登陆成功了
    
        def initTable(self, threshold=140):
            # 二值化函数
            table = []
            for i in range(256):
                if i < threshold:
                    table.append(0)
                else:
                    table.append(1)
            return table
    
        def img_to_str(self):  # 验证码识别(数字+字母组合),return一个识别成功的string
            # 替换列表--识别错误率高的手动添加进来,替换掉
            rep = {'O': '0', 'I': '1', 'Z': '2', "'": '', 'S': '8', 'R': 'A',
                   'n': 'M', 'P': 'f', 'M': 'n',
                   }
            images = Image.open("1.jpg")
            im = images.convert('L')
            binaryImage = im.point(self.initTable(), '1')
            text = pytesseract.image_to_string(binaryImage, config='-psm 7')
            for r in rep:
                text = text.replace(r, rep[r])
            vf_code = text.encode('utf-8')
            print('Pytesseract验证码识别:%s' % vf_code)
            return vf_code
    
    
    if __name__ == '__main__':
        url = '目标后台登陆地址'
        img_url = '目标随机验证码地址'  # 会自动下载图片并识别,成功率大概50%左右,可自行训练提高准确率
        username = '账号'
        password = '密码'
        SimulateLogin(url, username, password, img_url)


    运行代码:

    blob.png

关键字