版权声明:本文为博主手工码字内容,未经许可谢绝转载。 https://blog.csdn.net/qitianjin/article/details/80586809
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/20 16:21 # @Author : qitianjin # @Site : # @File : captcha.py # @Software: PyCharm Community Edition # from Python.work.procurement_gov.the_day import unittest_test from PIL import Image from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import random import sys from captcha_api import YDMHttp reload(sys) sys.setdefaultencoding('utf-8') from selenium.webdriver.support.select import Select from selenium.webdriver.common.action_chains import ActionChains class captcha(): # 生成验证码 def image_captcha(self,driver): driver.save_screenshot('./image/all.png') try: # //*[@id="im"] # //*[@id="im"] element = driver.find_element_by_xpath('''//*[@id="im"]''') if element: #x,y为起始位置坐标,width和height为图片 left = int(element.location['x']) top = int(element.location['y']) right = int(element.location['x'] + element.size['width']) bottom = int(element.location['y'] + element.size['height']) # 截取验证码的位置 im = Image.open('./image/all.png') im = im.crop((left, top, right, bottom)) im.save('./image/captcha.png') except Exception as e: print e # 返回识别后的字符串 def return_captcha(self): ###################################################################### # 用户名 username = '' # 密码 password = '' # 软件ID,开发者分成必要参数。登录开发者后台【我的软件】获得! appid = 1 # 软件密钥,开发者分成必要参数。登录开发者后台【我的软件】获得! appkey = '' # 图片文件 filename = './image/captcha.png' # 验证码类型,# 例:1004表示4位字母数字,不同类型收费不同。请准确填写,否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html codetype = 1004 # 超时时间,秒 timeout = 30 # 检查 if (username == 'username'): print '请设置好相关参数再测试' else: # 初始化 yundama = YDMHttp(username, password, appid, appkey) # 登陆云打码 uid = yundama.login() # 查询余额 balance = yundama.balance() # 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果 cid, result = yundama.decode(filename, codetype, timeout) result = result.encode('utf-8','ignore') return result def input_captcha(self,captcha,driver): driver.find_element_by_xpath('''//*[@id="i"]''').clear() elem = driver.find_element_by_xpath('''//*[@id="i"]''') elem.send_keys(captcha) elem.send_keys(Keys.ENTER) time.sleep(3) # def test_search_in_python_org(self): # #调用生成验证码 # self.image_captcha() # #打码测试返回数据 # captcha = self.return_captcha() # #输入验证码跳转主页 # self.input_captcha(captcha)
本文使用的是云打码平台,接口的使用说明写的很详细,上面的代码是生成图片,上传接口识别,输入字符串验证码的代码。
作者遇到的验证码是简单的数字字母四位组合。
扫描二维码关注公众号,回复:
2943767 查看本文章