1. 程式人生 > >Python 實現簡單圖片驗證碼登錄

Python 實現簡單圖片驗證碼登錄

需要 spa tps dem 圖片背景 round alt word exc

朋友說公司要在測試環境做接口測試,登錄時需要傳入正確的圖片的驗證碼,本著懶省事的原則,推薦他把測試環境的圖片驗證碼寫死,我們公司也是這麽做的^_^。勸說無果/(ㄒoㄒ)/~~,只能通過 OCR 技術來識別圖片驗證碼了,看了一下他們的驗證碼,長這樣技術分享,還好挺容易識別(背景色是透明的,有個坑需要處理)。

Python 實現了圖片驗證碼登錄 demo,用到的第三方模塊有 requests, PIL, pytesseract。

 1 # coding: utf-8
 2 import requests
 3 from PIL import Image
 4 from pytesseract import image_to_string, pytesseract
5 6 pytesseract.tesseract_cmd = D:\\env\\Tesseract-OCR\\tesseract 7 # url 8 base_url = https://hostxxx 9 code_url = base_url + /common-platform/code 10 do_login_url = base_url + /common-platform/doLogin 11 12 13 # 空白背景色 pytesseract 無法識別,更換了一下背景色 14 def change_background(img_fp): 15 try:
16 img = Image.open(img_fp) 17 x, y = img.size 18 new_img = Image.new(RGBA, img.size, (255, 255, 255)) 19 new_img.paste(img, (0, 0, x, y), img) 20 return new_img 21 except: 22 print u更換圖片背景失敗 23 24 25 # 識別圖片驗證碼 26 def ocr2str(img): 27 return
str(image_to_string(img)) 28 29 30 # 創建 session 31 session = requests.Session() 32 # 請求圖片驗證碼接口 33 code_resp = session.request(method=GET, url=code_url, verify=False) 34 # 保存圖片驗證碼 35 with open(code.png, wb) as f: 36 f.write(code_resp.content) 37 # 驗證碼 38 code = ocr2str(change_background(code.png)) 39 # 登錄數據 40 do_login_data = { 41 userName: user, 42 password: pwd, 43 verificationCode: code 44 } 45 # 登錄接口 46 do_login_resp = session.request(method=POST, url=do_login_url, data=do_login_data, verify=False) 47 print do_login_resp.text # 檢驗登錄是否成功


Python 實現簡單圖片驗證碼登錄