一、python实现读取验证码
from PIL import Image
import pytesseract
import os
import requests
import json
import base64
# 获取当前目录
dir = os.getcwd()
# 请求图片验证码
result = requests.get("https://xxxxxx.com/admin-api/auth/code")
img = json.loads(result.text)['data']['img']
# 将base64编码的图片数据解码
image_binary = base64.b64decode(img)
# 将二进制数据保存为图像文件
image_path = os.path.join(dir, 'captcha1.png')
with open(image_path, 'wb') as img_file:
img_file.write(image_binary)
# 如果你还没有设置Tesseract的路径,需要在这里设置(需要先安装tesseract)
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# 打开图像文件
image = Image.open('C:\\xx\\xx\\xx\\xx\\captcha1.png')
# 使用pytesseract提取图像中的文字
text = pytesseract.image_to_string("captcha1.png", lang='chi_sim')
# 去除多余的空格和换行符
text = text.replace(" ", "").replace("\n", "")
# 打印提取的文字(这里uuid因为后续接口需要做关联,所以我一起输出,如果没有用则直接返回图片验证码text参数即可)
二、apifox前置条件,调取Python图片验证码脚本
前置条件-自定义脚本如下:
#调取python脚本
const result = await pm.executeAsync('atest1.py');
# 分割多个参数
ss = result.split(" ")
console.log(ss[0]);
console.log(ss[1]);
# 设置环境变量
pm.environment.set("uuid", ss[0]);
pm.environment.set("code", ss[1]);