selenium UI自動化解決驗證碼的五種方法

 

 

 

 

TesseractPy3.pyjava

#coding=utf-8
 
import os
import subprocess
import traceback
import logging
 
from PIL import Image # 來源於Pillow庫
 
TESSERACT = 'tesseract' # 調用的本地命令名稱
TEMP_IMAGE_NAME = "temp.bmp" # 轉換後的臨時文件
TEMP_RESULT_NAME = "temp" # 保存識別文字臨時文件
CLEANUP_TEMP_FLAG = True # 清理臨時文件的標識
INCOMPATIBLE = True # 兼容性標識
 
def image_to_scratch(image, TEMP_IMAGE_NAME):
  # 將圖片處理爲兼容格式
  image.save(TEMP_IMAGE_NAME, dpi=(200,200))
 
def retrieve_text(TEMP_RESULT_NAME):
  # 讀取識別內容
  inf = open(TEMP_RESULT_NAME + '.txt','r')
  text = inf.read()
  inf.close()
  return text
 
def perform_cleanup(TEMP_IMAGE_NAME, TEMP_RESULT_NAME):
  # 清理臨時文件
  for name in (TEMP_IMAGE_NAME, TEMP_RESULT_NAME + '.txt', "tesseract.log"):
    try:
      os.remove(name)
    except OSError:
      pass
 
def call_tesseract(image, result, lang):
  # 調用tesseract.exe,將識讀結果寫入output_filename中
  args = [TESSERACT, image, result, '-l', lang]
  proc = subprocess.Popen(args)
  retcode = proc.communicate()
 
def image_to_string(image, lang, cleanup = CLEANUP_TEMP_FLAG, incompatible = INCOMPATIBLE):
  # 假如圖片是不兼容的格式而且incompatible = True,先轉換圖片爲兼容格式(本程序將圖片轉換爲.bmp格式),而後獲取識讀結果;若是cleanup=True,操做以後刪除臨時文件。
  logging.basicConfig(filename='tesseract.log')
  try:
    try:
      call_tesseract(image, TEMP_RESULT_NAME, lang)
      text = retrieve_text(TEMP_RESULT_NAME)
    except Exception:
      if incompatible:
        image = Image.open(image)
        image_to_scratch(image, TEMP_IMAGE_NAME)
        call_tesseract(TEMP_IMAGE_NAME, TEMP_RESULT_NAME, lang)
        text = retrieve_text(TEMP_RESULT_NAME)
      else:
        raise
    return text
  except: 
    s=traceback.format_exc()
    logging.error(s)
  finally:
    if cleanup:
      perform_cleanup(TEMP_IMAGE_NAME, TEMP_RESULT_NAME)

 

#coding=utf-8
 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from PIL import Image
import unittest, time, re
from TesseractPy3 import *
 
class lgoin(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Ie()
    self.driver.implicitly_wait(30)
    self.base_url = 'http://127.0.0.1:8080/test' # 要測試的連接
    self.title = '某管理平臺' # 測試網站的Title
    self.verificationErrors = []
    self.accept_next_alert = True
 
  def test_lgoin(self):
    driver = self.driver
    driver.get(self.base_url)
    driver.maximize_window()
    driver.save_screenshot('All.png') # 截取當前網頁,該網頁有咱們須要的驗證碼
    imgelement = driver.find_element_by_class_name('kaptchaImage')
    location = imgelement.location # 獲取驗證碼x,y軸座標
    size = imgelement.size # 獲取驗證碼的長寬
    rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])) # 寫成咱們須要截取的位置座標
    i = Image.open("All.png") # 打開截圖
    result = i.crop(rangle) # 使用Image的crop函數,從截圖中再次截取咱們須要的區域
    result.save('result.jpg')
    text = image_to_string('result.jpg', 'eng').strip()
 
    assert self.title in driver.title
 
    driver.find_element_by_id(u'userCode').clear()
    driver.find_element_by_id(u'userCode').send_keys('XXXXXX') # 用戶名
    driver.find_element_by_id(u'password').clear()
    driver.find_element_by_id(u'password').send_keys('XXXXXX') # 密碼
    #driver.find_element_by_name('verifyCode').clear()
    driver.find_element_by_name('verifyCode').send_keys(text)
    driver.find_element_by_name('submit').submit()
 
 
  def is_element_present(self, how, what):
    try: self.driver.find_element(by=how, value=what)
    except NoSuchElementException as e: return False
    return True
 
  def is_alert_present(self):
    try: self.driver.switch_to_alert()
    except NoAlertPresentException as e: return False
    return True
 
  def close_alert_and_get_its_text(self):
    try:
      alert = self.driver.switch_to_alert()
      alert_text = alert.text
      if self.accept_next_alert:
         alert.accept()
      else:
        alert.dismiss()
      return alert_text
    finally: self.accept_next_alert = True
 
  def tearDown(self):
    #self.driver.quit()
    self.assertEqual([], self.verificationErrors)
 
if __name__ == "__main__":
  unittest.main()

 

 

# coding=utf-8
 
from selenium import webdriver
import time 
 
driver = webdriver.Firefox()
driver.get("http://www.xxxxxx.com/") # 要登錄的網站
 
driver.add_cookie(cook) # 這裏添加cookie,有時cookie可能會有多條,須要添加屢次
time.sleep(3) 
 
# 刷新下頁面就能夠看到登錄成功了
driver.refresh() 

BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream("/Users/pangyongjuan/IdeaProjects/Zmbx/src/test/java/code.txt")));
​
        String code = null;
​
        while((code = reader.readLine()) != null){
            System.out.println("驗證碼是:---->"+ code);
            driver.findElement(By.id("pin")).sendKeys(code);
        }

 

相關文章
相關標籤/搜索