python 爬虫验证码模拟登陆
- 为什么要cookies
经验较少的朋友可能乍一看会以为IS_LOGIN是cookies的关键,其实不然。
我们先要简单了解一下cookies是个啥东西,有经验的朋友可以略过。
’“Cookie”是小量信息,由网络服务器发送出来以存储在网络浏览器上,从而下次这位独一无二的访客又回到该网络服务器时,可从该浏览器读回此信息。这是很有用的,让浏览器记住这位访客的特定信息,如上次访问的位置、花费的时间或用户首选项(如样式表)。Cookie 是个存储在浏览器目录的文本文件,当浏览器运行时,存储在 RAM 中。一旦你从该网站或网络服务器退出,Cookie 也可存储在计算机的硬驱上。当访客结束其浏览器对话时,即终止的所有 Cookie。(百度百科)
我们知道登录有个麻烦事就是验证码,这个对于后台来说其实也是个小麻烦,请求大家都发,后台怎么知道哪个验证码对应哪个浏览器发的请求?答案就是通过cookies。前端请求验证码的时候后台先用Set-Cookie的 response header将一个标识符带个前端浏览器,浏览器储存后下次发送登录请求的时候带上之前后台发过来的cookies,后台就知道是对应验证码的结果对不对了。
# -*-coding:utf-8 -*-
from __future__ import unicode_literals
import predict_code
import cv2
import requests
import time
import json
import sys
import cookielib
import urllib2
#防止中文出错
reload(sys)
sys.setdefaultencoding('utf-8')
def get_image_code():
''' 获取验证码并识别验证码返回 '''
global timestamp,opener
# 这是一个get请求,获取图片资源
image_code_url = "https://zre.com.cn/image/imageCheck?timestamp=" + str(timestamp)
res = opener.open(image_code_url).read()
with open("%s.jpg" % 'image_code', "wb") as f: # 将图片保存在本地
f.write(res)
image = cv2.imread('image_code.jpg')
#调用predict_code进行图片识别,具体参考博文(https://blog.csdn.net/weixin_40267472/article/details/81384624)
pre_code = predict_code.predict(image)
print '预测验证码为:%s' % (pre_code)
return pre_code
def login(username, password):
''' 模拟登陆 '''
pre_code = get_image_code()
headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Content-Length': '124',
'Content-Type': 'application/json;charset=UTF-8',
'Host': 'zb.cninfo.com.cn:3367',
'Origin': 'https://zre.com.cn:8080',
'Referer': 'https://zre.com.cn:8080/',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
}
datas = {
'checkCode': pre_code,
'imageCode': timestamp,
'password': password,
'username': username,
}
posturl = 'https://user/login'
response = requests.post(url=posturl, data=json.dumps(datas), headers=headers)
res_content = response.content
json_dict = json.loads(response.text)
# 判断登陆失败,则重新登陆
if json_dict['code'] != 0:
res_content = login(username, password)
print res_content
print '登陆成功!'
return res_content
if __name__ == "__main__":
global opener, timestamp
cookie = cookielib.CookieJar() # 声明一个CookieJar对象实例来保存cookie
handler = urllib2.HTTPCookieProcessor(cookie) # 利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
opener = urllib2.build_opener(handler) # 通过handler来构建opener
timestamp = unicode(long(time.time() * 1000))
username = 'sixiaoyuan'
password = '123456'
login(username, password)