古诗文网验证码识别,是通过对古诗文网登陆界面的验证码图片进行识别的,利用专门的验证码识别网站,可以提取验证码图片中的验证码
网站推荐:超级鹰
import requests
from lxml import etree
'''1. 导入Chaojiying中的Chaojiying_Client类
最好确保Chaojiying文件和当前py文件在同级目录下'''
from Chaojiying import Chaojiying_Client
import os
# 2. 将解析图片中的验证码封装成一个方法
def getCode(filePath):
//2.1 只需要修改用户名、密码和软件ID即可
chaojiying = Chaojiying_Client('超级鹰用户名', '超级鹰用户名的密码', '96001') #用户中心>>软件ID 生成一个替换 96001
//2.2 需要修改从古诗文网中爬取验证码图片的路径
im = open(filePath, 'rb').read() #本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, 1902)) #1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加()
# 3. 创建一个文件夹,存放验证码图片
if not os.path.exists('./gushi'):
os.mkdir('./gushi')
# 4. 获取页面中的验证码图片
url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56',
'Cookie': '__cfduid=da7f51b97bb9f9e2236b55baf8a0ef6bd1612596271; Hm_lvt_526caf4e20c21f06a4e9209712d6a20e=1612596274; zkhanecookieclassrecord=%2C54%2C56%2C60%2C66%2C65%2C; Hm_lpvt_526caf4e20c21f06a4e9209712d6a20e=1612598106'
}
page_text = requests.get(url = url,headers = headers).text
tree = etree.HTML(page_text)
# 5. 观察可发现爬取的src和图片真实地址之间的关系
'''真实地址: https://so.gushiwen.cn/RandCode.ashx
src: /RandCode.ashx'''
img_src = "https://so.gushiwen.cn" + tree.xpath('//div[@class="mainreg2"]//img/@src')[1]
img_path = './gushi/1.jpg'
# 6. 下载二维码图片并保存到本地
img_content = requests.get(url = img_src,headers = headers).content
with open(img_path,'wb') as fp:
fp.write(img_content)
# 7. 调用识别方法,识别验证码
getCode(img_path)
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()