# coding: utf-8
import requests
from PIL import Image
from pytesseract import image_to_string, pytesseract
pytesseract.tesseract_cmd = 'D:\\env\\Tesseract-OCR\\tesseract'
# url
base_url = 'https://hostxxx'
code_url = base_url + '/common-platform/code'
do_login_url = base_url + '/common-platform/doLogin'
# 空白背景色 pytesseract 无法识别,更换了一下背景色
def change_background(img_fp):
try:
img = Image.open(img_fp)
x, y = img.size
new_img = Image.new('RGBA', img.size, (255, 255, 255))
new_img.paste(img, (0, 0, x, y), img)
return new_img
except:
print u'更换图片背景失败'
# 识别图片验证码
def ocr2str(img):
return str(image_to_string(img))
# 创建 session
session = requests.Session()
# 请求图片验证码接口
code_resp = session.request(method='GET', url=code_url, verify=False)
# 保存图片验证码
with open('code.png', 'wb') as f:
f.write(code_resp.content)
# 验证码
code = ocr2str(change_background('code.png'))
# 登录数据
do_login_data = {
'userName': 'user',
'password': 'pwd',
'verificationCode': code
}
# 登录接口
do_login_resp = session.request(method='POST', url=do_login_url, data=do_login_data, verify=False)
print do_login_resp.text # 检验登录是否成功