python+Selenium+Pytesseract登入時自動識别驗證碼
一直想試着使用python+selenium+pytesseract來做一下驗證碼識别。
按照網上提供的方法嘗試了一下,大體的功能能實作。
(參考:https://www.jianshu.com/p/afcde49c57b7)
就是想吐槽一下,這個識别的成功率真是不高。。。。
補充兩點:
一、識别出來的驗證碼,有時候包含空格或者特殊字元。
可以使用下面的正規表達式除去
import re
code = pytesseract.image_to_string(img)
code = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", code)
二、驗證碼正常一次是識别不出來,需要多識别幾次。
可以使用while循環
while True:
# 清空驗證碼輸入框
d.find_element_by_css_selector('input[placeholder="請輸入驗證碼"]').clear()
# 找到驗證碼img标簽,切圖
img_code = d.find_element_by_id('authCode')
# 算出驗證碼的四個點,即驗證碼四個角的坐标位址
left = img_code.location['x']
top = img_code.location['y']
right = img_code.location['x'] + img_code.size['width']
bottom = img_code.location['y'] + img_code.size['height']
print("驗證碼坐标::", left, top, right, bottom)
# 利用python的PIL圖檔處理庫,利用坐标,切出驗證碼的圖
im = Image.open('login.png')
# 電腦設定的顯示縮放比例為150%
im = im.crop((left * 1.5, top * 1.5, right * 1.5, bottom * 1.5))
# im = im.convert('L') # 轉換模式:L | RGB
im = ImageEnhance.Contrast(im) # 增強對比度
im = im.enhance(2.0) # 增加飽和度
im.save('code.png')
# 調用圖檔識别的函數,得到驗證碼
code = self.img_to_str()
if code:
# 找到驗證碼的input,并輸入驗證碼
d.find_element_by_css_selector('input[placeholder="請輸入驗證碼"]').send_keys(code)
# 點選登入按鈕
d.find_element_by_css_selector('button[ng-click="fSub()"]').click()
sleep(5)
if 'index' in d.current_url:
print(d.current_url)
print("登入成功")
break
else:
d.find_element_by_css_selector('button[class="btn btn-success"]').click()
print("No match!!")
這個方法需要在輸入錯誤的驗證碼後,能自動更新驗證碼圖檔。
注:文章内容主要是記錄學習過程中遇到的一些問題,以及解決方法。留個記錄,同時分享給有需要的人。如有不足之處,歡迎指正,謝謝!