Web自動化測試之圖文驗證碼的解決方案

對於web應用程序來講,處於安全性考慮,在登錄的時候,都會設置驗證碼, 驗證碼的類型種類繁多,有圖片中辨別數字字母的,有點擊圖片中指定的文字的,也有算術計算結果的,再復雜一點就是滑動驗證的。 諸如此類的驗證碼,對我們的系統增加瞭安全性的保障,但是對於我們測試人員來講,在自動化測試的過程中,無疑是一個棘手的問題。

1、Web 化驗證碼解決方案

一般在我們測試過程中,登錄遇到上述的驗證碼的時候,有以下種解決方案:

  • 第一種、讓開發去掉驗證碼
  • 第二種、設置一個萬能的驗證碼
  • 第三種、通過 cookie 繞過登錄
  • 第四種、自動識別技術識別驗證碼

2、驗證碼解決方案

# coding:utf-8
import os
import subprocess
from PIL import Image

def get_captcha(driver, captcha_id, full_screen_img_path, captcha_img_path, captcha_final_path, txt_path, ocr_path):
# 瀏覽器界面截圖
driver.save_screenshot(full_screen_img_path)
# 找到驗證碼圖片,得到它的坐標
element = driver.find_element_by_id(captcha_id)
left = element.location['x']
top = element.location['y']
right = element.location['x'] + element.size['width']
bottom = element.location['y'] + element.size['height']
left, top, right, bottom = int(left), int(top), int(right), int(bottom)
img = Image.open(full_screen_img_path)
img = img.crop((left, top, right, bottom))
# 得到驗證碼圖片
img.save(captcha_img_path)
# 打開驗證碼圖片
img = Image.open(captcha_img_path)
# 顏色直方圖,255種顏色,255為白色
# 新建一張圖片(大小和原圖大小相同,背景顏色為255白色)
img_new = Image.new('P', img.size, 255)
for x in range(img.size[1]):
for y in range(img.size[0]):
# 遍歷圖片的xy坐標像素點顏色
pix = img.getpixel((y, x))
# print(pix)
# 自己調色,r=0,g=0,b>0為藍色
if pix[0] < 20 and pix[1] < 20 and pix[2] > 50:
# 把遍歷的結果放到新圖片上,0為透明度,不透明
img_new.putpixel((y, x), 0)
img_new.save(captcha_final_path, format='png')

# 通過tesseract工具解析驗證碼圖片,生成文本
os.system(ocr_path)

# 讀取txt文件裡面的驗證碼
with open(txt_path, 'r') as f:
if f.read():
t = f.read().strip()
# 去掉中間空格
if ' ' in t:
t = t.replace(' ', '')
if t.isdigit() and len(t) == 4:
return t
else:
return 'fail'

def check_resp(result, msg):
if msg in result:
return 'pass'
else:
return 'failed'

# 接口 - 識別驗證碼
def get_captcha(captcha_img_path, captcha_final_path, txt_path, ocr_path):

# 打開驗證碼圖片
img = Image.open(captcha_img_path)

# 新建一張圖片(大小和原圖大小相同,背景顏色為255白色)
img_new = Image.new('P', img.size, 55)
for x in range(img.size[1]):
for y in range(img.size[0]):
# 遍歷圖片的xy坐標像素點顏色
pix = img.getpixel((y, x))
# print(pix)
# 自己調色,r=0,g=0,b>0為藍色
if pix[0] < 20 and pix[1] < 20 and pix[2] > 50:
# 把遍歷的結果放到新圖片上,0為透明度,不透明
img_new.putpixel((y, x), 0)
img_new.save(captcha_final_path, format='png')

# 通過tesseract工具解析驗證碼圖片,生成文本,【Tesseract-OCR必須和jpg的根目錄必須相同,如C盤、D盤!!!】
os.system(ocr_path)

# 讀取txt文件裡面的驗證碼
with open(txt_path, 'r') as f:
if r.read():
t = f.read().strip()
# 去掉中間空格
if ' ' in t:
t = t.replace(' ', '')
# 如果是數字且長度為4,就返回數字,如果不是就返回 fail
if t.isdigit() and len(t) == 4:
return t
else:
return fail

赞(0)