一、在自動化測試中,遇到驗證碼的處理方法有以下兩種:
1、找開發去掉驗證碼或者使用萬能驗證碼
2、使用OCR自動識別
這里,方法一只要和研發溝通就行。
使用pytesseract自動化識別,一般識別率不是太高,處理一般簡單驗證碼還是沒問題,例如下面這種驗證碼:

使用非常簡單,只需下面幾步:
import pytesseractfrom PIL import Imageimage=Image.open('new.jpg')vcode=pytesseract.image_to_string(image)PRint vcode
二、但在使用python自動化測試中會遇到一個難點,驗證碼怎么獲取,python的webdriver API沒有這樣接口。baidu查之,網上只有java的解決方案,python的貌似沒有,在這就將python的解決方案寫下,以供需要的人參考:
解決方法:
從頁面獲取驗證碼的坐標值得,使用PIL的Image模塊,截取特定的區域,代碼如下:
思路:將web節目截圖保存-->定位到驗證碼坐標-->從截圖中再進行驗證碼位置的截圖
from PIL import Imageimport pytesseractfrom selenium import webdriverurl='http://xxxxx.com'driver = webdriver.Chrome()driver.maximize_window() #將瀏覽器最大化driver.get(url)driver.save_screenshot('f://aa.png') #截取當前網頁,該網頁有我們需要的驗證碼imgelement = driver.find_element_by_xpath('//img[@src="rand!loginRand.action"]') #定位驗證碼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("f://aa.png") #打開截圖frame4=i.crop(rangle) #使用Image的crop函數,從截圖中再次截取我們需要的區域frame4.save('f://frame4.jpg')QQ=Image.open('f://frame4.jpg')text=pytesseract.image_to_string(qq).strip() #使用image_to_string識別驗證碼print text
參考模塊:
Image模塊:http://effbot.org/imagingbook/image.htm
pytesseract識別驗證碼方法:http://www.waitalone.cn/python-php-ocr.html
新聞熱點
疑難解答