一、環境準備
1.Pycharm安裝第三方庫:
PIL
pytesseract
2.電腦安裝軟件:
tesseract-ocr
版本:tesseract-ocr-w64-setup-v5.0.0.20190526
下載地址:https://digi.bib.uni-mannheim.de/tesseract/
百度雲下載地址:https://pan.baidu.com/s/1of1yUdmAW9i5LUS1cGumFg
提取碼:yy3b
3.設置環境變量:
編輯path:新增tesseract-ocr安裝路徑
新增TESSDATA_PREFIX:tesseract-ocr安裝路徑下的tessdata文件夾路徑
4.驗證環境配置是否符合要求
5.找一張驗證碼圖片試一下
二、實現代碼
from PIL import Image
from http import cookiejar
import urllib.request, urllib.parse, urllib.error
# import sys
import time
import pytesseract
class AuthCode():
def get_verification_code(self,time):
f = None
try:
cookieJar = cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookieJar))
# 找一個帶驗證碼圖片的網頁,獲取驗證碼圖片
url = '*****' + time
print(url)
res = opener.open(url)
response=res.read()
with open('D:\\auth_code_image\\auth_code.jpg', 'wb') as f:
f.write(response)
# 使用PIL打開一個圖片,轉換成灰度模式
l_image = Image.open('D:\\auth_code_image\\auth_code.jpg').convert('L')
# 使用image_to_string識別驗證碼
py_text = pytesseract.image_to_string(l_image).strip()
print(py_text)
# res_text = []
# for i in py_text:
# if i != ' ':
# res_text.append(i)
# text = ''.join(res_text)
# print(text)
except urllib.error.HTTPError as e:
raise Exception("連接失敗:%s" % e)
finally:
if f:
f.close()
return py_text
millis = str(int(round(time.time() * 1000)))
auth_api = AuthCode()
res = auth_api.get_verification_code(millis)
print(res)