python爬虫----DAY4-1-----验证码识别实战
实战:识别古诗文网登录页面中的验证码 —https://so.gushiwen.cn/user/login.aspx
使用超级鹰平台识别验证码的编码流程:
-将验证码图片进行本地下载
-调用平台提供的示例代码进行图片数据识别
分析
其他详细操作写在代码注释中
代码
import requests
from lxml import etree
from ChaoJiYin import Chaojiying_Client
# 0. 封装打码平台函数
#第一个参数输入验证码路径,第二个参数为验证码类型
#最后返回一个字典,取出需要的数据
def getCodeText(imgPath, codeType):
chaojiying = Chaojiying_Client('1257965244', 'yihen0214', '919873') # 用户中心>>软件ID 生成一个替换 96001
im = open(imgPath, 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, codeType))
return chaojiying.PostPic(im, codeType)
# 1. 指定url
url='https://so.gushiwen.cn/user/login.aspx'
# 2. UA伪装
headers={
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67'
}
# 3. 发起请求
page_text=requests.get(url=url,headers=headers).text
# 4. 数据解析
tree=etree.HTML(page_text)
# https://so.gushiwen.cn/RandCode.ashx 完整地址
code_url="https://so.gushiwen.cn"+tree.xpath('//*[@id="imgCode"]/@src')[0]
#5. 对验证码发起请求,获取验证码图片,图片是二进制数据,用.content
code=requests.get(url=code_url,headers=headers).content
#6. 存储验证码图片
with open("code.jpg",'wb') as fp:
fp.write(code)
#7. 调用打码平台,识别验证码
#4~6为英文、数字类型为1902
detail=getCodeText("./code.jpg",1902)
print(detail["pic_str"])
结果展示
验证码识别前置内容,第三方打码平台使用
上面的看不了可以看看这个
python爬虫-古诗文网验证码识别