selenium中验证码识别简单封装
先简单封装一下,后续也可将定位元素方法封装,直接调用方法,
import random
import string
import time
import pickle
from lib.ShowapiRequest import ShowapiRequest
from PIL import Image
import os
# 对识别验证码进行封装
def get_code(driver,xpath):
# 获取验证码图片
t = time.time()
# 保存到当前项目下Screen下
path = os.path.dirname(os.path.dirname(__file__))+'\\Screen'
picture_name1=path +'\\'+str(t)+'.png'
driver.save_screenshot(picture_name1)
code = driver.find_element_by_xpath(xpath)
print(code.location)
left = code.location['x']
top = code.location['y']
right = code.size['width'] + left
height = code.size['height'] + top
dpr = driver.execute_script('return window.devicePixelRatio')
print(dpr)
im = Image.open(picture_name1)
# 抠验证码区域图
code_img = im.crop((left * dpr, top * dpr, right * dpr, height * dpr))
picture_name2= path + '\\' + str(t) + '.png'
# picture_name2 = str('yzm2') + '.png'
code_img.save(picture_name2)
# 调用验证码识别api
r = ShowapiRequest("http://route.showapi.com/184-4", "xxx", "xxx")
r.addFilePara("image", picture_name2)
r.addBodyPara("typeId", "34")
r.addBodyPara("convert_to_jpg", "0")
r.addBodyPara("needMorePrecise", "0")
res = r.post()
text = res.json()['showapi_res_body']
code_text = text['Result']
return code_text
# 生成随机字符串
def gen_random_str():
rand_str = ''.join(random.sample(string.ascii_letters+string.digits,8))
return rand_str
# 保存cookies
def save_cookie(driver,path):
with open(path,'wb') as filehandler:
cookies = driver.get_cookies()
print(cookies)
pickle.dump(cookies,filehandler)
# 加载cookies
def load_cookies(driver,path):
with open(path,'rb') as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)