python—简单数据抓取四(利用超级鹰的ocr识别图片验证码模拟登录超级鹰网站、利用百度云的ocr识别自如租房网价格图片获取到自如网的价格)

学习目标:

python学习二十四 —简单数据抓取四


学习内容:

1、利用超级鹰的ocr识别图片验证码模拟登录超级鹰网站
2、利用百度云的ocr识别自如租房网的价格图片,获取到自如网的价格数据


1、利用超级鹰的图片识别图片验证码模拟登录超级鹰网站

import requests
from hashlib import md5
import requests
import re
import pymysql
from lxml import etree

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        self.password = md5(password.encode('utf8')).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()


if __name__ == '__main__':

# 需要的header头部
    headers = {
        'authority': 'www.chaojiying.com',
        'referer': 'https://www.chaojiying.com/',
        'origin': 'https://www.chaojiying.com',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    }

# 用session记录cookie的状态,因为此网站的cookie可变,注意后面对该网站的所有请求均是以h开头	 
    h = requests.Session()

# 首先获取登录界面的图片验证码
    source = h.get('https://www.chaojiying.com/user/login/', headers=headers).text
    img = 'https://www.chaojiying.com/'+etree.HTML(source).xpath('/html/body/div[3]/div/div[3]/div[1]/form/div/img/@src')[0]
    pic = h.get(img, headers=headers).content

# 并将图片保存 到本地
    op = open('F:\pycharm\lx\chaojiying\/a.jpg', 'wb')
    op.write(pic)
    op.close()


# 超级鹰的图片识别区
    chaojiying = Chaojiying_Client('17158232693', 'yytax245.', '912200')  # 用户中心>>软件ID 生成一个替换 96001
  
   # 取出本地的图片,并读取
    im = open('F:\pycharm\lx\chaojiying\/a.jpg', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    
    # 1902是超级鹰的价格模型,针对不同类型的图片验证码的价格编号
    pic_str = chaojiying.PostPic(im, 1902)['pic_str']
    print(pic_str)

# data是用户登录需要的数据
    data = {
        'user': '超级鹰用户名',
        'pass': '超级鹰密码',
        'imgtxt': pic_str,
        'act': '1',
    }

# post登录连接,带上header头和用户需要的data数据
    a = h.post('https://www.chaojiying.com/user/login/', headers=headers, data=data).text
    
    # get获取到登录成功页面的代码
    index = h.get('https://www.chaojiying.com/user/', headers=headers).text
    print(index)

2、利用百度云的ocr识别自如租房网的价格图片,获取到自如网的价格数据

from lxml import etree
import requests
import re
from decimal import Decimal
import base64

headers = {
    'User-Agent': 'Mozilla/5.0(Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}

# 获取到自如租房的房间页面的代码
source =requests.get('http://tj.ziroom.com/x/754539414.html', headers=headers).text
print(source)
# 获取到该房间的价格每个数字的位置px,以及所对应数字串的序列(每次请求该数字序列在变化)图片
url = etree.HTML(source).xpath('/html/body/section/aside/div[1]/i/@style')

# 创建一个列表存放数字的位置px
px = []
# 创建一个字符串存放数字串的序列图片
pic = ''

# 循环取出价格中的每个数字位置以及序列图片
for i in url:
    # 用正则匹配出数字位置信息和序列图片的链接
    demo = re.compile('background-position:-(.*?)px;background-image: url\((.*?)\);')
    lists = demo.findall(i)
    # 将数字位置信息存放到px列表中
    px.append(lists[0][0])
    # 拼凑出数字序列图片的url
    pic = 'http:'+ lists[0][1]
print(px, pic)

# 创建一个字典用来0到9的十个数字分别对应一个位置信息
dicts = {}
# 其中为了防止python计算小数时不够精确,所以用了Decimal包用来精确计算数字的位置小数
n = Decimal('0')

for i in range(10):
    if n != 0:
        nn = float(n)
    else:
        nn=0
# 创建一个0到9对应31.24倍数的一个字典
    dicts[str(nn)]=i
    n += Decimal('31.24')
print(dicts)

# 按自如网中给出价格的位置信息取出本地字典对应数字即第几个数字
index = [dicts[x] for x in px]
print(index)

# 将数字序列图片存进到本地
pic_source = requests.get(pic, headers=headers).content
op = open('F:\pycharm\lx\ziru\/' + pic.split('/')[-1], 'wb')
op.write(pic_source)
op.close()

'''
网络图片文字识别(含位置版)
'''

request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage_loc"
# 二进制方式打开图片文件
f = open('F:\pycharm\lx\ziru\\'+pic.split('/')[-1], 'rb')
img = base64.b64encode(f.read())



# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=百度智能云的API Key码&client_secret=百度智能云的Secret Key码'
response = requests.get(host)
if response:
    print(response.json())

params = {"image":img}
access_token = response.json()['access_token']
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print(response.json())

# 按格式取出数字序列
words = response.json()['words_result'][0]['words']
print(words)
# 按index中元素的值,取出words中相应位置的数字,并拼在一起
price = ''.join([words[x] for x in index])
print(price)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值