1. 程式人生 > 程式設計 >Python完全識別驗證碼自動登入例項詳解

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已執行完第 ",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完全識別驗證碼自動登入例項詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。