一、使用pytesseract轉(zhuǎn)換
安裝方法:
pip install pytesseract
示例如下:
pytesseract.image_to_string(這里傳驗(yàn)證碼圖片)
二、使用tesseract_ocr轉(zhuǎn)換
安裝方法:
pip install tesseract_ocr
示例如下:
tesseract_ocr.text_for_filename(這里傳驗(yàn)證碼圖片)
三、使用tesseract轉(zhuǎn)換
安裝方法:
brew install tesseract
示例如下:
from selenium import webdriver
from PIL import Image
from PIL import ImageOps
import subprocess
try:
path = '/Users/dawei/Downloads/captcha.png' # 驗(yàn)證碼圖片路徑
resultTxtPath = '"/Users/dawei/Downloads/captcha"' # 識(shí)別后的圖片驗(yàn)證碼內(nèi)容路徑(不包含擴(kuò)展名)
wd = webdriver.Firefox() # 創(chuàng)建火狐
wd.get('http://www.bycoming.com/hrd/hrd_login.do') # 打開(kāi)登錄頁(yè)
wd.save_screenshot(path) # 保存截圖
# 從截圖中裁剪驗(yàn)證碼圖片
img = Image.open(path)
loc = wd.find_element_by_id('img_code').location # 獲取驗(yàn)證碼圖片的位置
size = wd.find_element_by_id('img_code').size # 獲取驗(yàn)證碼圖片的大小
box = (loc['x'], loc['y'], float(loc['x']) + float(size['width']), float(loc['y']) + float(size['height']))
img = img.crop(box) # 裁剪出驗(yàn)證碼圖片
img.save(path) # 保存驗(yàn)證碼圖片
img = img.point(lambda x: 0 if x < 143 else 255) # 處理圖片上的每個(gè)像素點(diǎn),使圖片上每個(gè)點(diǎn)“非黑即白”
borderImage = ImageOps.expand(img, border=20, fill='white')
borderImage.save(path)
p = subprocess.Popen(["tesseract", path, resultTxtPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
f = open("/Users/dawei/Downloads/captcha.txt", "rb")
b = f.read()
s = b.decode()
print('識(shí)別結(jié)果:', s.replace('\n', '').replace(' ', ''))
except:
print('except!')
finally:
print('finally!')
wd.quit()