实验三:验证码处理与识别
实验目的
针对常见的验证机制:验证码进行分析和识别,可以使用传统和 OCR 技术或者基于神经网络的机器学习技术
环境
- Selenium 库,PyQuery 库,Chrome 和对应的 ChromeDr iver
- 深度机器学习库和图像处理库: pytorch, python-opencv
- OCR 库: python 第三方模块 tesserocr(这里我使用的是 pytesseract)
实验要求 1
使用一个合适的技术将登录网站 1 的验证码进行识别,并由代码自动登录。注意事项:所有信息必须由代码自动填入并且自动操作,如果人工填入任何信息或使用人工交互,此项目不得分。
实验过程
需要导入的包
import time
import numpy as np
import pytesseract
from PIL import Image
import re
from selenium import webdriver
from retrying import retry
from io import BytesIO
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
# retrying库是用来设置浏览器重登次数的,io库是用来获取图片的
处理验证码
- pytesseract 将图像识别为文本
txt = pytesseract.image_to_string(image)
# 将处理验证码的方法封装成一个函数方便调用
def process_image(image):
"""
图片处理函数提取出正确的验证码
:param image: 验证码图片
:return: 返回字符串
"""
# 将图片转换为灰度图像,只有黑和白两种颜色
demo = image.convert('L')
# 将图像转换为多维数组
arr = np.array(demo)
# 设置灰度阈值
threshold = 100
# 进行筛选,超过阈值的像素变为白色,没有超过的变为黑色
arr = np.where(arr > threshold, 255, 0)
# 将筛选过的数组又转换为图像
final_image = Image.fromarray(arr.astype('uint8'))
# 将图像内容识别为文本
txt = pytesseract.image_to_string(final_image)
# 匹配
result = re.sub(r'\W', "", txt)
return result