爬虫之验证码识别

一、验证码识别
1.反爬机制:验证码、识别验证码图片中的数据,用于模拟登陆操作
2.识别验证码的操作:
1)人工肉眼识别(不推荐)
2)第三方自动识别(推荐)
- 超级鹰
二、实战:识别超级鹰登陆页面中的验证码

-超级鹰所提供的的代码

-在个人库中将其定义为yh

#!/usr/bin/env python
 coding:utf-8

import requests
from hashlib import md5

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
            self.username = username
            password =  password.encode('utf8')
            self.password = md5(password).hexdigest()
            self.soft_id = soft_id
            self.base_params = {
     
                'user': self.username,
                'pass2': self.password,
                'softid': self.soft_id,
            }
            self.headers = {
     
                'Connection': 'Keep-Alive',
                'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
            }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
     
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {
     'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
     
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()


 在这里调用的时候把相应的信息放进去(账号密码软件id,就不用重复的放了)
 留两个参数使其调用更加灵活
 code_path是验证码的图片的路径
 code_type是验证码的类型
def get_code(code_path, code_type):
	chaojiying = Chaojiying_Client('用户名', '用户密码', '软件ID')	#用户中心>>软件ID 生成一个替换 96001
	im = open(code_path, 'rb').read()													#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
	return chaojiying.PostPic(im, code_type)												#1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加())

超级鹰登录页面验证码识别

import yh #引入个人的库
from lxml import etree #解析数据
import requests

url = 'http://www.chaojiying.com/user/login/' #随便找一个有验证码的页面
headers = {
     
	    'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0',
}     #UA伪装
page = requests.get(url = url,headers=headers).text  #获取文本格式的响应
tree = etrss.HTML(page) #解析数据
code_img_src = 'http://www.chaojiying.com' + tree.xpath('/html/body/div[3]/div/div[3]/div[1]/form/div/img/@src')[0]  #渠道图片的链接
print(code_img_src)   #打印图片链接
code_img_data = requests.get(url = code_img_src,headers=headers).content
with open('./code.jpg','wb') as fp: #存图片
	fp.write(code_img_data) 

code = yh.get_code('./code.jpg','1004)
print(code) # 打印实验结果

你可能感兴趣的:(爬虫入门)