python 使用OCR识别登录验证码
分享一下玩OCR的过程, 因为咱们后台登录的时候经常都会让输入验证码, 每次验证码都不相同, 搞自动化就有了一个不得不翻越的问题.
首先我们要去百度智能云申请一个账号.(申请后百度工作人员会电话问你用的如何如何...)
我开通的是 通用文字识别(标准版) ,会给免费使用次数(每月1000次超出后收费) 用来玩玩或者平时使用足矣
最关键的是获取到API Key 和 Secret Key

官方也给了一个python的调用示例 仅供参考 https://cloud.baidu.com/doc/OCR/s/Pkrwx9ye4
今天的知识点:
requests 库的GET/POST请求
图片文件保存
图片文件转base64编码
知识点比较简单 就不过多介绍了
思路:
1.获取验证码图片
2.图片down下来保存
3.获取OCR token
4.将图片base64编码后上传识别
5.对识别数字做优化
上源码:
import requests import base64 def get_captcha(): """ 获取验证码 """ url = "https://manager.xiongmaozhanggui.com/user/login/captcha" headers = { "Content-Type": "application/json" } resp = requests.get(url=url, headers=headers) if resp.status_code == 200: return resp.content else: print("接口返回值不是200") def save_img(img_bytes): """ 保存图片到本地 """ filepath = ".\\img\\captcha.png" with open(file=filepath, mode="wb") as f: f.write(img_bytes) return filepath def get_file_base64(filePath): """ 文件编码为 base64 """ with open(filePath, 'rb') as f: image = f.read() image_base64 = str(base64.b64encode(image), encoding='utf-8') return image_base64 def get_baidu_token(): """ 你的 APPID AK SK """ API_KEY = 'wCPtCltgYC9HffOPiRzN...' SECRET_KEY = 'qT2DfsPC8kpX4OaYIgtO6Gc4f2g2...' params = { 'grant_type': 'client_credentials', 'client_id': API_KEY, 'client_secret': SECRET_KEY } url = 'https://aip.baidubce.com/oauth/2.0/token' response = requests.get(url, params=params) if response: return response.json() def ocr(access_token, img_base64): """ 识别图片 """ url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic' params = { "access_token": access_token } data = { "image": img_base64, "language_type": "ENG" } header = { "Content-Type": "application/x-www-form-urlencoded" } response = requests.post(url, params=params, data=data, headers=header) if response: return response.json() def Optimization(words): """ 只保留数字 """ string = '' for s in words: try: if int(s): string += s except ValueError as e: pass return string def run(): # 1获取验证码图片 img_bytes = get_captcha() # 2保存图片 img_path = save_img(img_bytes) # 3获取百度OCR token resp = get_baidu_token() access_token = resp['access_token'] # 4图片base64编码 image = get_file_base64(img_path) # 5识别图片 resp = ocr(access_token, image) words = resp['words_result'][0]['words'] print("识别验证码:", words) # 6只保留数字 nums = Optimization(words) print("优化验证码:", nums) if __name__ == '__main__': run()
上效果图:


浙公网安备 33010602011771号