python 验证码识别

来源:互联网 发布:剑客软件抢购怎么样 编辑:程序博客网 时间:2024/05/16 14:32

登录网站,遇到验证码如何处理?
一、 在输入验证码框内,通过人眼识别,手动输入验证码。
二、 通过对验证码进行识别,让程序去处理。
利弊分析:
手动输入的利与弊
利:介于light平台的验证码并不复杂,可以认为,手动输入验证码的准确率是100%。
弊:碰上验证码都需要手动输入,无疑会占用一点点时间。
程序处理的利于弊:
利:这一点不必多说,完全自动化。
弊:程序识别验证码准确率并非100%,有时候是非常低的,可能1/4、1/5乃至更低的准确识别率。
实现方案:
选择了第二个方案,通过程序处理识别验证码。虽然可能处理五次才能成功一次,但是对于程序处理来说,也就几秒钟的时间,在时间上并不会比手动输入更慢。
对于验证码识别,python需要安装的库有:
1、 PIL(安装需要BeautifulSoup4支持)——对图片进行处理
2、 tesseract-ocr ——光学识别(将图片上的信息转换成文字)

识别验证码流程:
1、 访问验证码网址
2、 截图保存
3、 对图片进行处理,使之更易被光学识别
4、 进行光学处理(通俗点就是图片信息转换成文本信息)
5、 对处理后文本进行处理(主要是:去掉空格、换行)
6、 对最终的文本信息做一个基本判断(light平台的验证码都是四位或五位,若验证码识别文本长度不是四位或五位,就可以认为识别失败)
以下代码是简化了过程,着重识别验证码这一个步骤。

import subprocessfrom PIL import Imagefrom PIL import ImageOpsdef cleanImage(imagePath):    image = Image.open(imagePath)   #读取文件    image = image.point(lambda x: 0 if x<143 else 255)  #对像素点处理    borderImage = ImageOps.expand(image,border=20,fill='white') #图片延伸    borderImage.save(imagePath) #保存def getAuthCode(file, driver="a", url="b"):    # captchaUrl = url + "iuccasserver/captcha.jpg"   #图片路径    # driver.get(captchaUrl)    # time.sleep(0.5)    # driver.save_screenshot("captcha.jpg")   #验证码截图    #urlretrieve(captchaUrl, "captcha.jpg")    # cleanImage("captcha.jpg")   #图片处理    cleanImage(file)   #图片处理    p = subprocess.Popen(["tesseract", file, "captcha"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)    p.wait()    f = open("captcha.txt", "r")    #Clean any whitespace characters    captchaResponse = f.read().replace(" ", "").replace("\n", "")    print("Captcha solution attempt: "+captchaResponse)    if (len(captchaResponse) == 4) or (len(captchaResponse) == 5):        return captchaResponse    else:        return Falseprint(getAuthCode("captcha.jpg"))print(getAuthCode("captcha4.jpg"))print(getAuthCode("captcha5.jpg"))

上述验证码处理函数为:
clean_img

上述代码中光学识别语句为:
p = subprocess.Popen([“tesseract”, “captcha.jpg”, “captcha”], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
以上代码也可以在dos窗口下输入命令:
tesseract
如上命令,执行后会生成文件 captcha.txt文件
有以下三张图,可以作为一个验证数据
captcha.jpg
0
captcha4.jpg
4
captcha5.jpg
5

注:这篇文章是对之前文章“python+selenium识别验证码并登录”的补充。文章地址为:http://blog.csdn.net/ck3207/article/details/51711559

原创粉丝点击