python爬虫--古诗文网的模拟登陆(验证码识别)
验证码识别登录古诗文网
请求参数:
级鹰代码:
#!/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()
def codecjy():
chaojiying = Chaojiying_Client('tjtjtj', 'tangjian219', '902590')#用户中心>>软件ID 生成一个替换 96001
im = open('yzm.jpg', 'rb').read()#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
code=chaojiying.PostPic(im, 1902)['pic_str']#1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加()
return code
爬虫程序:
import requests
from lxml import etree
session = requests.Session() #实例化一个session对象
url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx' #登陆页面的url
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
}
page_img_text = session.get(url=url,headers=headers).text
tree = etree.HTML(page_img_text)
img_url=tree.xpath('//*[@id="aspnetForm"]/div[4]/div[4]/img/@src')[0] #获取验证码图片的url
new_img_url = 'https://so.gushiwen.org/'+ img_url #验证码图片的全路径拼接
login_url = 'https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fcollect.aspx' #点击登陆按钮发送的请求url
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
}
img=session.get(new_img_url,headers=headers).content #请求图片
# 对验证码图片的下载
with open('./yzm.jpg','wb') as f:
f.write(img)
img_code = codecjy() #验证码
print(img_code)
VIEWSTATE=tree.xpath('//*[@id="__VIEWSTATE"]/@value') #发送post请求携带的动态参数
VIEWSTATEGENERATOR=tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')#发送post请求携带的动态参数
data={
'__VIEWSTATE': VIEWSTATE,
'__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR,
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email': '15032551128',
'pwd': 'tangjian219',
'code': img_cod, #验证码
'denglu': '登录',
}
new_page_text = session.post(url=login_url,headers=headers,data=data).text
with open('./gushiwen.html','w',encoding='utf-8') as fp:
fp.write(new_page_text)