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


Posted in Python onNovember 24, 2019

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开发常用的一些开源Package分享
Feb 14 Python
python实现清屏的方法
Apr 30 Python
Python中datetime常用时间处理方法
Jun 15 Python
python检查序列seq是否含有aset中项的方法
Jun 30 Python
详解python的webrtc库实现语音端点检测
May 31 Python
Python连接phoenix的方法示例
Sep 29 Python
python如何创建TCP服务端和客户端
Aug 26 Python
python查找指定文件夹下所有文件并按修改时间倒序排列的方法
Oct 21 Python
Pytorch .pth权重文件的使用解析
Feb 14 Python
使用Python项目生成所有依赖包的清单方式
Jul 13 Python
带你学习Python如何实现回归树模型
Jul 16 Python
Django日志及中间件模块应用案例
Sep 10 Python
关于Python 常用获取元素 Driver 总结
Nov 24 #Python
pyhton中__pycache__文件夹的产生与作用详解
Nov 24 #Python
使用Python实现画一个中国地图
Nov 23 #Python
用Python画小女孩放风筝的示例
Nov 23 #Python
python实现对列表中的元素进行倒序打印
Nov 23 #Python
Python实现打印实心和空心菱形
Nov 23 #Python
在Python中使用turtle绘制多个同心圆示例
Nov 23 #Python
You might like
基于文本的访客签到簿
2006/10/09 PHP
php socket方式提交的post详解
2008/07/19 PHP
php expects parameter 1 to be resource, array given 错误
2011/03/23 PHP
php日历制作代码分享
2014/01/20 PHP
PHP的mysqli_thread_id()函数讲解
2019/01/24 PHP
PHP扩展类型及安装方式解析
2020/04/27 PHP
clientX,pageX,offsetX,x,layerX,screenX,offsetLeft区别分析
2010/03/12 Javascript
页面加载完后自动执行一个方法的js代码
2014/09/06 Javascript
做web开发 先学JavaScript
2014/12/12 Javascript
JS控制弹出新页面窗口位置和大小的方法
2015/03/02 Javascript
javascript显式类型转换实例分析
2015/04/25 Javascript
JavaScript实现表格点击排序的方法
2015/05/11 Javascript
javascript判断图片是否加载完成的方法推荐
2016/05/13 Javascript
JavaScript——DOM操作——Window.document对象详解
2016/07/14 Javascript
JavaScript和jQuery获取input框的绝对位置实现方法
2016/10/13 Javascript
利用Angularjs中模块ui-route管理状态的方法
2016/12/27 Javascript
JS 组件系列之Bootstrap Table的冻结列功能彻底解决高度问题
2017/06/30 Javascript
vue如何搭建多页面多系统应用
2020/06/17 Javascript
[03:38]TI4西雅图DOTA2前线报道 71专访
2014/07/08 DOTA
[01:32]TI珍贵瞬间系列(一)
2020/08/26 DOTA
Python基于sklearn库的分类算法简单应用示例
2018/07/09 Python
对pandas将dataframe中某列按照条件赋值的实例讲解
2018/11/29 Python
selenium+python自动化测试之页面元素定位
2019/01/23 Python
python三引号输出方法
2019/02/27 Python
python实现两张图片拼接为一张图片并保存
2019/07/16 Python
python操作excel让工作自动化
2019/08/09 Python
Tensorflow进行多维矩阵的拆分与拼接实例
2020/02/07 Python
python使用列表的最佳方案
2020/08/12 Python
详解用selenium来下载小姐姐图片并保存
2021/01/26 Python
SQL Server面试题
2016/10/17 面试题
OLEDBConnection和SQLConnection有什么区别
2013/05/31 面试题
5个HTML5的常用本地存储方式详解与介绍
2021/03/27 HTML / CSS
合作经营协议书
2014/04/17 职场文书
学校学习雷锋活动总结
2014/07/03 职场文书
2015社区六五普法工作总结
2015/04/21 职场文书
幼儿园辞职信
2015/05/13 职场文书