反爬与反反爬(二)图片验证码

8.图片验证码

1.什么是图片验证码
  • 验证码(CAPTCHA)全自动区分计算机和认类的图灵测试,是一种区分用户是计算机还是人的全自动程序

1.1验证码的作用

  • 防止恶意破解密码、剧票、论坛灌水、刷页。

1.2图片验证码在爬虫中的使用场景

  • 注册
  • 登录
  • 频发发送请求时,服务器弹出验证码进行验证

1.3图片验证码的处理方案

  • 手动输入这种方法仅限于登录一次就可持续使用的情况
  • 图像识别引擎解析,使用光学识别引擎处理图片中的数据,目前常用与图片数据提取,较少勇于验证码处理
  • 打码平台,爬虫常用的验证码解决方案
2.图片识别引擎

OCR是指使用扫描仪或数码相机对文本资料进行扫描成图像文件,然后对图像文件进行分析处理,自动识别获取文字信息或版面信息的软件。

2.1什么是tesseract

  • Tesseract,一款由HP实验室开发由Google维护的开源ORC引擎,特点是开源、免费、支持多语言多平台
  • 项目地址:https://github.com/tesseract-ocr/tesseract

2.2图片识别引擎环境的安装

  • 1.引擎的安装

    mac环境下直接执行命令

    brew insall --with-training-tools tesseract
    

    windows环境下的安装 可以通过exe安装包安装,下载地址可以从GitHub项目的wiki找到。安装完成后记得将Tesseract执行文件的目录加入到PATH中,方便后续调用。

    linux环境下的安装

    sudo apt-agt install tesseract-ocr
    
  • 2.Python库的安装

    # PIL用户打开图片文件
    pip install pillow
    
    # pytesseract模块勇于从图片中解需数据
    pip install pytesseract
    

2.3图片识别引擎的使用

  • 通过pytesseract模块的image_to_string方法就能打开图片文件中的数据提取字符串数据,具体方法如下:

    from PIL import Image
    import pytesseract
    
    im = Image.open("test.jpg")
    result = pytesseract.image_to_string(im)
    print(result)
    
3.打码平台

3.1为什么需要了解打码平台的使用

现在很多网站都会使用验证码来进行反爬,所以能够为了更好的获取数据,需要了解如何使用打码平台爬虫中的验证码

3.2常见的打码平台

  • 云打码 http://www.yundama.com/
  • 极验验证码智能识别辅助 http://jiyandoc.c2567.com/

3.3云打码的使用

下面以云打码为例,了解打码平台如何使用

从平台的开发文档中下载示例文件

例如代码:

import http.client, mimetypes, urllib, json, time, requests

######################################################################

class YDMHttp:

    apiurl = 'http://api.yundama.com/api.php'
    username = ''
    password = ''
    appid = ''
    appkey = ''

    def __init__(self, username, password, appid, appkey):
        self.username = username  
        self.password = password
        self.appid = str(appid)
        self.appkey = appkey

    def request(self, fields, files=[]):
        response = self.post_url(self.apiurl, fields, files)
        response = json.loads(response)
        return response
    
    def balance(self):
        data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['balance']
        else:
            return -9001
    
    def login(self):
        data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response = self.request(data)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['uid']
        else:
            return -9001

    def upload(self, filename, codetype, timeout):
        data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
        file = {'file': filename}
        response = self.request(data, file)
        if (response):
            if (response['ret'] and response['ret'] < 0):
                return response['ret']
            else:
                return response['cid']
        else:
            return -9001

    def result(self, cid):
        data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid)}
        response = self.request(data)
        return response and response['text'] or ''

    def decode(self, filename, codetype, timeout):
        cid = self.upload(filename, codetype, timeout)
        if (cid > 0):
            for i in range(0, timeout):
                result = self.result(cid)
                if (result != ''):
                    return cid, result
                else:
                    time.sleep(1)
            return -3003, ''
        else:
            return cid, ''

    def report(self, cid):
        data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid), 'flag': '0'}
        response = self.request(data)
        if (response):
            return response['ret']
        else:
            return -9001

    def post_url(self, url, fields, files=[]):
        for key in files:
            files[key] = open(files[key], 'rb');
        res = requests.post(url, files=files, data=fields)
        return res.text

######################################################################

# 用户名
username    = 'morganna'

# 密码
password    = '461324morganna'

# 软件ID,开发者分成必要参数。登录开发者后台【我的软件】获得!
appid       = 1                                     

# 软件密钥,开发者分成必要参数。登录开发者后台【我的软件】获得!
appkey      = '22cc5376925e9387a23cf797cb9ba745'    

# 图片文件
filename    = 'getimage.jpg'                        

# 验证码类型,# 例:1004表示4位字母数字,不同类型收费不同。请准确填写,否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
codetype    = 1004

# 超时时间,秒 
timeout     = 60                                    

# 检查
if (username == 'username'):
    print('请设置好相关参数再测试')
else:
    # 初始化
    yundama = YDMHttp(username, password, appid, appkey)

    # 登陆云打码
    uid = yundama.login()
    print('uid: %s' % uid)

    # 查询余额
    balance = yundama.balance()
    print('balance: %s' % balance)

    # 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
    cid, result = yundama.decode(filename, codetype, timeout)
    print('cid: %s, result: %s' % (cid, result))

######################################################################

4.常见的验证码种类

4.1url地址不变,验证码不变

这事验证码里面非常简单的一种类型,对应的只需要获取验证码的地址,然后请求,通过打码平台识别即可

4.2url地址不变,验证码变化

更加常见的一种类型,对于这种类型的验证码,需要思考:

在登录的过程中,假设我输入的验证码是对的,对方服务器如何判断当前我输入的验证码是显示在我屏幕上的验证码,而不是其他的验证码呢?

在获取网页的时候,请求验证码,以及提交验证码的时候,对方服务器肯定通过了某种手段验证我之前获取的验证码和最后提交的验证码是同一个验证码,那这个手段是什么手段呢?

很明显,就是通过cookie来实现,所以对应的,在请求页面,请求验证码,提交验证码的到时候需要保证cookie的一致性,对此可以使用requests.session来解决

你可能感兴趣的:(反爬与反反爬(二)图片验证码)