在使用Python做自動化時候遇到登錄需要識別驗證碼問題,此時采用pytesseract模塊,遇到例外:
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.
解決方式:
1、下載對應版本的“Tesseract-OCR”,下載地址:https://github.com/tesseract-ocr/tesseract/wiki 或者 https://github.com/UB-Mannheim/tesseract/wiki
下載檔案名稱:tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe
2、安裝Tesseract-OCR,請記住安裝路徑,
3、配置環境變數:
(1)配置Tesseract-OCR環境變數:
將Tesseract-OCR的安裝路徑配置在環境變數Path中,D:\Program Files\python38\Lib\site-packages\Tesseract-OCR ,如下圖:

(2)配置tessdata環境變數:
新增一個變數名:TESSDATA_PREFIX,變數值為安裝的Tesseract-OCR路徑下的tessdata的路徑,即,在Tesseract-OCR的安裝路徑后追加tessdata,D:\Program Files\python38\Lib\site-packages\Tesseract-OCR\tessdata,如下圖

4、然后將pytesseract.py原始碼中
tesseract_cmd = 'tesseract'
修改為:
tesseract_cmd = r'D:\Program Files\python38\Lib\site-packages\Tesseract-OCR\tesseract.exe'
重新運行腳本,OK
如下圖所示的登錄頁面,

附帶識別驗證碼代碼:
from selenium import webdriver from PIL import Image import pytesseract def readvcode(): dr = webdriver.Chrome("D:\softwarePro\BrowserDriver\chromedriver.exe") dr.maximize_window() dr.get(url) dr.save_screenshot('All.png') # 截取當前網頁,該網頁有我們需要的驗證碼 imgelement = dr.find_element_by_class_name('imgcode') 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("All.png") # 打開截圖 result = i.crop(rangle) # 使用Image的crop函式,從截圖中再次截取我們需要的區域 result.save('result.png') text = pytesseract.image_to_string('result.png', 'eng').strip() dr.find_element_by_name("username").send_keys("admin") dr.find_element_by_name("password").send_keys("admin123") dr.find_element_by_name("validateCode").send_keys(text) dr.find_element_by_id("btnSubmit").click() if __name__ == '__main__': readvcode()
帶有噪點或者劃線類的驗證碼以后更新,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232303.html
標籤:Python
上一篇:舔狗福利來了,python教你舔狗舔到量的質變變成海王
下一篇:Window下安裝Python
