摘要:测试过程中经常遇到图片验证码,以下主要是调用百度OCR图片识别获取验证码,实现登录
1、百度云申请创建应用
- 2、调用接口提取图片验证码
# -*- coding:utf-8 -*-
import requests,json
from comm import api_demo
url = "https:// "
head = {
"Content-Type":"application/json"
}
def image_get():
# 发送get请求,r 接收接口响应
r = requests.get(url=path,headers=head)
# 打印响应信息,提取image
text = json.loads(r.text)
image = text['data']['image'].split(",")[1] # 提取自己需要的图片地址
print(image)
# print(type(image),f'列表{image.split(",")}')
# print(text,'\n' ,type(text))
# print(text['data']['image'])
if __name__ == '__main__':
image_get()
3、将验证码保存到本地
"""http链接格式图片"""
# import requests
#
# def save_image_from_url(image_url, save_path):
# response = requests.get(image_url)
# if response.status_code == 200:
# with open(save_path, 'wb') as file:
# file.write(response.content)
# print("图片保存成功!")
# else:
# print("下载图片失败。")
#
# # 调用函数并传入图片地址和保存路径
# image_url = "https://aaa.png"
# save_path = "C:/Users/starry.zhang.477/Desktop/image.jpg"
# save_image_from_url(image_url, save_path)
"""base64格式图片"""
import base64
import io
from PIL import Image # pip install pillow
def save_image_from_base64(image_base64,save_path):
image_data = base64.b64decode(image_base64)
image = Image.open(io.BytesIO(image_data))
image.save(save_path)
print("图片保存成功!")
# 调用函数并传入base64编码的图片和保存路径 -- 注意:data:image/png;base64, 该信息代表编码格式不必传参
image_base64 = "你的base64编码的图片"
save_path = "C:\\Users\starry.zhang.477\Desktop\image.png"
if __name__ == '__main__':
save_image_from_base64(image_base64,save_path)
- 4、调用百度OCR-api识别验证码
# 先安装对用插件
pip install baidu-aip
pip install chardet
# 百度ocr提供了模板,直接复制
# 下载通用文字识别的python sdk,一定要放在你写的代码的文件夹下面
from aip import AipOcr
def baiduOCR(picfile): # picfile:你需要识别的图片文件名
# 百度提供
""" 你的百度API APPID AK SK """
APP_ID = '******' # 百度API的appid
API_KEY = '************************' # 百度API的appkey
SECRET_KEY = '*****************************' # 百度API的secretkey
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
i = open(picfile, 'rb')
img = i.read()
""" 调用通用文字识别(高精度版) """
message = client.basicAccurate(img)
i.close()
# 输出文本内容
for text in message.get('words_result'): # 识别的内容
print(text.get('words'))
if __name__ == '__main__':
baiduOCR('C:\\Users\starry.zhang.477\Desktop\image.png')