- 原理 : 使用requests给验证码图片的url发送http请求(支持json或者form-data),将图片保存在本地(性能测试建议存储在nfs中),调用pillow模块中的Image和pytesseract对图片进行解析,最后使用requets发送登录请求,form-data会使用到requests_toolbelt
- 环境准备 :
pip install pytesseract
pip install pillow
pip install requests
pip install requests_toolbelt
- requests使用方法(传参为json/form-data):
r = requests.post[*http请求方法](url,data=json.dumps("key":"value"))
m = MultipartEncoder(
fields={'field0': 'value', 'field1': 'value',
'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
)
r = requests.post('http://httpbin.org/post', data=m,
headers={'Content-Type': m.content_type})
参考文档:https://2.python-requests.org//zh_CN/latest/user/quickstart.html
- 根据requests的功能与预期结果比验证判断接口是否成功
r.text: 返回response
r.json(): 以json格式返回
r.status_code: 返回状态码
r.cookies: 获取cookies
r.url: 判断发送请求的url (针对reference url)
r.headers: 获得请求头消息等
- 验证码获取
code = pytesseract.image_to_string(Image.open(r'/图片路径'))
参考文档: https://pillow.readthedocs.io/en/stable/reference/Image.html#examples
代码示例
import pytesseract
from PIL import Image
import requests
from requests_toolbelt import MultipartEncoder
class Py_demo:
def __init__(self):
pass
def get_img(self,url,img_name):
get_img = requests.get(url)
print(get_img.url)
if get_img.status_code != 200:
print("get image failed")
return False
else:
print("get image success,downloading~")
with open(img_name,'wb') as file:
file.write(get_img.content)
def get_code(self):
global sakura
sakura = pytesseract.image_to_string(Image.open(r'/Users/sakurahappy/Desktop/CaptchaImg.png'))
if len(sakura) < 3:
print("get code failed,try again")
else:
print("get code success")
print(sakura)
return sakura
def log_in(self,url,username,password,sakura):
m = MultipartEncoder(fields={'username': username, 'password': password,'checkCode':sakura,'clientsystem':'mactrue','clientscreensize':'1440,900','clientbrowser':'chrome74'})
# print(m.content_type)
# print(username,password,sakura)
print(url)
r = requests.post(url, data=m,headers={'Content-Type': m.content_type},allow_redirects=False)
r = requests.get(img_url,cookies=r.cookies)
print(r.status_code)
print(r.url)
if r.status_code == 200:
print("cookies is ok,login success~")
return True
else:
print("cookies is invalue, login failed")
return False
if __name__=='__main__':
demo = Py_demo()
get_img = demo.get_img(img_url,'CaptchaImg.png')
get_code = demo.get_code()
log_in = demo.log_in(url,username,password,sakura)
网友评论