Python网络爬虫实验三:验证码处理与识别

实验三:验证码处理与识别

实验目的

针对常见的验证机制:验证码进行分析和识别,可以使用传统和 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

设置重登次数


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值