本文介紹了python selenium UI自動化解決驗證碼的4種方法,分享給大家,具體如下:
測試環(huán)境
selenium UI自動化解決驗證碼的4種方法:去掉驗證碼、設(shè)置萬能碼、驗證碼識別技術(shù)-tesseract、添加cookie登錄,本次主要講解驗證碼識別技術(shù)-tesseract和添加cookie登錄。
1. 去掉驗證碼
去掉驗證碼,直接通過用戶名和密碼登陸網(wǎng)站。
2. 設(shè)置萬能碼
設(shè)置萬能碼,就是不管什么情況,輸入萬能碼,都可以成功登錄網(wǎng)站。
3. 驗證碼識別技術(shù)-tesseract
準(zhǔn)備條件
安裝好Python,通過pip install pillow安裝pillow庫。然后將tesseract中的tesseract.exe和testdata文件夾放到測試腳本所在目錄下,testdata中默認(rèn)有eng.traineddata和osd.traineddata,如果要識別漢語,請自行下載對應(yīng)包。
以下是兩個主要文件,TesseractPy3.py是通過python代碼去調(diào)用tesseract以達(dá)到識別驗證碼的效果。code.py是通過selenium獲取驗證碼圖片,進(jìn)而使用TesseractPy3中的函數(shù)得到驗證碼,實現(xiàn)網(wǎng)站的自動化登陸。
TesseractPy3.py
#coding=utf-8import osimport subprocessimport tracebackimport loggingfrom PIL import Image # 來源于Pillow庫TESSERACT = 'tesseract' # 調(diào)用的本地命令名稱TEMP_IMAGE_NAME = "temp.bmp" # 轉(zhuǎn)換后的臨時文件TEMP_RESULT_NAME = "temp" # 保存識別文字臨時文件CLEANUP_TEMP_FLAG = True # 清理臨時文件的標(biāo)識INCOMPATIBLE = True # 兼容性標(biāo)識def image_to_scratch(image, TEMP_IMAGE_NAME): # 將圖片處理為兼容格式 image.save(TEMP_IMAGE_NAME, dpi=(200,200))def retrieve_text(TEMP_RESULT_NAME): # 讀取識別內(nèi)容 inf = open(TEMP_RESULT_NAME + '.txt','r') text = inf.read() inf.close() return textdef 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: passdef call_tesseract(image, result, lang): # 調(diào)用tesseract.exe,將識讀結(jié)果寫入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,先轉(zhuǎn)換圖片為兼容格式(本程序?qū)D片轉(zhuǎn)換為.bmp格式),然后獲取識讀結(jié)果;如果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)
新聞熱點
疑難解答