一、使用pytesseract转换
安装方法:
pip install pytesseract
示例如下:
pytesseract.image_to_string(这里传验证码图片)
二、使用tesseract_ocr转换
安装方法:
pip install tesseract_ocr
示例如下:
tesseract_ocr.text_for_filename(这里传验证码图片)
三、使用tesseract转换
安装方法:
brew install tesseract
示例如下:
from selenium import webdriver
from PIL import Image
from PIL import ImageOps
import subprocess
try:
path = '/Users/dawei/Downloads/captcha.png' # 验证码图片路径
resultTxtPath = '"/Users/dawei/Downloads/captcha"' # 识别后的图片验证码内容路径(不包含扩展名)
wd = webdriver.Firefox() # 创建火狐
wd.get('http://www.bycoming.com/hrd/hrd_login.do') # 打开登录页
wd.save_screenshot(path) # 保存截图
# 从截图中裁剪验证码图片
img = Image.open(path)
loc = wd.find_element_by_id('img_code').location # 获取验证码图片的位置
size = wd.find_element_by_id('img_code').size # 获取验证码图片的大小
box = (loc['x'], loc['y'], float(loc['x']) + float(size['width']), float(loc['y']) + float(size['height']))
img = img.crop(box) # 裁剪出验证码图片
img.save(path) # 保存验证码图片
img = img.point(lambda x: 0 if x < 143 else 255) # 处理图片上的每个像素点,使图片上每个点“非黑即白”
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('识别结果:', s.replace('\n', '').replace(' ', ''))
except:
print('except!')
finally:
print('finally!')
wd.quit()