Python完全识别验证码自动登录实例详解

yipeiwu_com6年前Python基础

1、直接贴代码

#!C:/Python27
#coding=utf-8
 
 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from pytesser import *
from PIL import Image,ImageEnhance,ImageFilter
from selenium.common.exceptions import NoSuchElementException,TimeoutException
import os,time
 
 
 
 
def before():
 
 
  driver.get(src)
 
 
  time.sleep(1)
 
 
  driver.maximize_window() # 浏览器全屏显示
 
 
  print ('\n浏览器全屏显示 ...')
 
 
 
 
 
 
def Convertimg():
  
  imglocation = ("//*[@id='loginForm']/div[4]/div[2]/img[1]")
  
  #下载验证码图片保存到本地
  driver.save_screenshot('E:\\pythonScript\\Codeimages\\code.png')
  
  #打开本地图片
  im = Image.open('E:\\pythonScript\\Codeimages\\code.png')
 
 
  left = driver.find_element_by_xpath(imglocation).location['x']
  top = driver.find_element_by_xpath(imglocation).location['y']
  right = driver.find_element_by_xpath(imglocation).location['x'] + driver.find_element_by_xpath(imglocation).size['width']
  bottom = driver.find_element_by_xpath(imglocation).location['y'] + driver.find_element_by_xpath(imglocation).size['height']
 
 
  im = im.crop((left, top, right, bottom))
 
 
  im.save('E:\\pythonScript\\Codeimages\\screenshot.png')
 
 
  print u"\n保存验证码图片完成"
 
 
  #移除截屏的图片
 
 
  os.remove('E:\\pythonScript\\Codeimages\\code.png')
 
 
  print u"\n删除截屏图片完成"
 
 
  #处理验证码图片
  src = ('E:\\pythonScript\\Codeimages\\screenshot.png')
 
 
  #调用裁剪图片方法
  Cutedge(src)
 
 
  #移除截屏的图片
  os.remove('E:\\pythonScript\\Codeimages\\screenshot.png')
  #灰化图片处理
  im = Image.open('E:\\pythonScript\\Codeimages\\CutedgeImage.png')
  
  imgry = im.convert('L')
  #二值化处理
 
 
  threshold = 100
  table = []
  for i in range(256):
    if i < threshold:
      table.append(0)
    else:
      table.append(1)
  out = imgry.point(table, '1')
 
 
  out.save('E:\\pythonScript\\Codeimages\\rgb.png')
 
 
  #vcode = pytesseract.image_to_string(out)
 
 
  #print (vcode)
 
 
  txtcode = image_to_string(out)
 
 
  print u"\n识别出验证码文字为:",image_to_string(out)
 
 
  print len(txtcode.strip())
 
 
  print
 
 
  if len(txtcode.strip()) == 4:
 
 
      print u"长度相等"
               
  else:
      print u"长度不相等,退出"
      
      driver.quit()
 
 
  #输入用户名和密码
  driver.find_element_by_id("username").send_keys("123456")
 
 
  driver.find_element_by_id("password").send_keys("123456")
 
 
  time.sleep(2)
 
 
  #对文本框输入验证码值
  driver.find_element_by_id("verifyCode").send_keys(txtcode.strip())
 
 
  time.sleep(3)
  #点击登录  
  driver.find_element_by_xpath("//*[@id='loginForm']/div[5]/div/img").click()
  #driver.find_element_by_class_name('loginbtn').click()
  time.sleep(7)
  
  
#针对有黑色边框的验证码图片的裁剪边缘  
def Cutedge(src):
  
  #设置要裁剪的区域
  im = Image.open(src)
  
  w, h = im.size
  
  print u"\n验证码原图宽、高尺寸为:",w,h
  
  box = (2,2,110,30)
  
  im.crop(box).save('E:\\pythonScript\\Codeimages\\CutedgeImage.png')
 
 
  print u"\n保存裁剪的图片 CutedgeImage.png"
 
 
#  
src = ("https://www.test.com")
 
 
driver = webdriver.Chrome() #Firefox()#
 
 
def method_2(src):
   
  before()
 
 
  #调用图片裁剪方法
  Convertimg()
 
 
  
def clickInput():
 
 
  driver.find_element_by_id("inputButton").click()
 
 
  print "\nInput Click Finish"
 
 
def clickOutput():
 
 
  print u"\n开始执行点击事件"
 
 
  #开始执行点击事件      inputButton
  driver.find_element_by_id("outputButton").click()
 
 
  time.sleep(2)
 
 
  print (u'\n开始执行任务,执行间隔时间为10分钟 ...')
 
 
 
 
 
 
  for i in range(1,4):
 
 
    ISOTIMEFORMAT="%Y-%m-%d %X"
  
    strTime = time.strftime( ISOTIMEFORMAT, time.localtime())
 
 
    driver.refresh()
 
 
    print u"\n正在执行第 ",i,"次...",strTime
  
    time.sleep(5)
  
    driver.find_element_by_id("outputButton").click()
  
    time.sleep(30)
  
    print
    #刷新浏览器
    print u"\n刷新当前页面 ..."
  
    driver.refresh()
  
    print (u'\n等待间隔时间为9分钟 ...')
  
    time.sleep(505)
  
    print u"\n已执行完第 ",i,u"次,",u"已等待",i*10,u"分钟"
   
  print (u'\n已执行完成...At The End OF,'+strTime)
  
  driver.quit()
 
 
def isPass():
  try:     
    #driver.find_element_by_id("username").is_displayed() == True
  
    driver.find_element_by_id('status').text == (u"验证码不正确!")
    
    print (u"\n****校验提示信息_验证码输入不正确****")
 
 
    driver.quit()
 
 
    print (u"\n关闭浏览器,执行外层循环...")
  
  except Exception:
    print (u"\n****校验提示信息_验证码输入正确****")
 
 
    clickOutput() #------  click Output
  
method_2(src) #进入工作页面
 
 
isPass()
 
 
#clickInput() #------  click Input
 
 
#clickOutput() #------  click Output
 
 
 
 
for i in range(1,6):
 
 
  driver = webdriver.Chrome()
  
  src = ("https://www.test.com")
 
 
  method_2(src)
 
 
  isPass()
  
  #clickOutput()
 

2、控制台日志

浏览器全屏显示 ...
 
获取到元素的文本值为: 
 
保存验证码图片完成
 
删除截屏图片完成
 
验证码原图宽、高尺寸为: 113 34
 
保存裁剪的图片 CutedgeImage.png
 
识别出验证码文字为: gnbn
 
 
 
开始执行任务,执行间隔时间为10分钟 ...
 
正在执行第 1 次... 2017-05-25 18:10:24
 
刷新当前页面 ...
 
等待间隔时间为9分钟 ...

以上这篇Python完全识别验证码自动登录实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python的Flask框架中构建Web表单的教程

在Python的Flask框架中构建Web表单的教程

尽管Flask的request对象提供的支持足以处理web表单,但依然有许多任务会变得单调且重复。表单的HTML代码生成和验证提交的表单数据就是两个很好的例子。 Flask-WTF扩展使...

Python复制Word内容并使用格式设字体与大小实例代码

简介 网上流传的部分可以百度关键词“Python”和“word”后查看文章学习,以下内容为个人实践,修正了不能运行出错的情况。 代码示例 import win32com from...

Python语言进阶知识点总结

Python语言进阶知识点总结

数据结构和算法 算法:解决问题的方法和步骤 评价算法的好坏:渐近时间复杂度和渐近空间复杂度。 渐近时间复杂度的大O标记: - 常量时间复杂度 - 布隆过滤器 / 哈希存储 - 对数时间复...

用Python编写脚本使IE实现代理上网的教程

厂里上个网需要设置代理服务器,切换各种环境『包括但不仅限于开发环境、QA、预上线、验收、生产环境、压力测试、Demo……』都需要给浏览器设置不同的代理服务器。 虽然俺有神器Firefox...

快速了解Python中的装饰器

需要理解的一些概念 要理解Python中的装饰器,我觉得还是应该从最基本的概念开始: 装饰器模式:所谓的装饰器模式,可以简单地理解为“在不改变原有内部实现的情况下,为函数或者类添加某种特...