验证码打码平台的对接。
1、打码平台的配置。
#!/usr/bin/env python # coding:utf-8 import requests from hashlib import md5 import shandong_config class Chaojiying_Client(object): def __init__(self, username, password, soft_id): self.username = username password = password.encode('utf-8') self.password = md5(password).hexdigest() self.soft_id = soft_id self.base_params = { 'user': self.username, 'pass2': self.password, 'softid': self.soft_id, } self.headers = { 'Connection': 'Keep-Alive', 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', } def PostPic(self, im, codetype): """ im: 图片字节 codetype: 题目类型 参考 http://www.chaojiying.com/price.html """ params = { 'codetype': codetype, } params.update(self.base_params) files = {'userfile': ('ccc.jpg', im)} r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers) return r.json() def ReportError(self, im_id): """ im_id:报错题目的图片ID """ params = { 'id': im_id, } params.update(self.base_params) r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers) return r.json() def get_code(filename, code_type): ''' 获取验证码结果 :param img_path: 图片路径,可以是相对路径或绝对路径 :param code_type: 验证码类型,详情可见:http://www.chaojiying.com/price.html :return: ''' chaojiying = Chaojiying_Client(shandong_config.DAMA_USERNAME, shandong_config.DAMA_PASSWORD, shandong_config.DAMA_TOKEN) im = open(filename, 'rb').read() #本地图片文件路径 来替换 a.jpg 有时WIN系统须要// code = chaojiying.PostPic(im, code_type)['pic_str'] #1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加() return code
2、验证码的获取。
# 验证码 self.browser.save_screenshot('./image/shandong/printscreen.png') imgelement = self.browser.find_element_by_id('image') location = imgelement.location # 获取验证码x,y轴坐标 size = imgelement.size # 获取验证码的长宽 rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) # 写成我们需要截取的位置坐标 i = Image.open("./image/shandong/printscreen.png") # 打开截图 frame4 = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域 frame4.save('./image/shandong/save.png') # 保存我们接下来的验证码图片 进行打码
3.对接。
element = self.wait.until(EC.presence_of_element_located((By.ID, 'verifyCode'))) element.send_keys(get_code('./image/shandong/save.png',1902))