selenium和pytessarct提取古诗文网的验证码(python爬虫)

代码实现的主要功能:

  1. 浏览器自动化控制

  2. 验证码图像获取与处理

  3. OCR验证码识别

  4. 表单自动填写与提交

  5. 登录状态验证

  6. 异常处理与资源清理

1. 浏览器初始化与页面加载
python 复制代码
driver = webdriver.Chrome()
driver.get("https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx")
time.sleep(2)
  • 功能:启动Chrome浏览器并打开古诗文网登录页面

  • 关键点

    • webdriver.Chrome() 初始化浏览器驱动

    • time.sleep(2) 确保页面完全加载(实际建议改用 WebDriverWait

2.验证码捕获与预处理
python 复制代码
code_img = driver.find_element(By.ID, 'imgCode')
img_bytes = code_img.screenshot_as_png
image = Image.open(io.BytesIO(img_bytes))
image = image.convert('L')  # 灰度化
  • 功能:获取验证码图像并优化识别条件

  • 关键点

    • screenshot_as_png 直接获取二进制图像数据

    • convert('L') 将彩色图转为灰度图,提升OCR准确率

    • 注释掉的二值化代码可用于高对比度验证码

3. OCR验证码识别
python 复制代码
custom_config = r'--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
textcode = pytesseract.image_to_string(image, config=custom_config)
textcode = textcode.strip().replace(' ', '')[:4]
  • 功能:通过Tesseract引擎识别验证码文本

  • 关键参数

    • --psm 7:单行文本识别模式

    • --oem 3:默认OCR引擎

    • tessedit_char_whitelist:限定识别字符集

  • 数据处理:去除空格并截取前4位字符

4. 登录表单操作
python 复制代码
driver.find_element(By.ID, 'email').send_keys("2833622025@qq.com")
driver.find_element(By.ID, 'pwd').send_keys("ckn12138")
driver.find_element(By.ID, 'code').send_keys(textcode)
driver.find_element(By.ID, 'denglu').click()
  • 功能:自动填写并提交登录表单

  • 元素定位

    • 通过HTML元素的ID定位各输入框

    • denglu 是登录按钮的ID

5. 登录结果验证
python 复制代码
if "退出登录" in driver.page_source:
    print("登录成功!")
    html = driver.page_source
else:
    print("登录失败,请检查账号或验证码!")
  • 验证逻辑:检查页面是否出现"退出登录"文本

  • 成功操作:获取登录后的页面源码

  • 失败处理:输出错误提示

6. 异常处理与资源释放
python 复制代码
except Exception as e:
    print("程序运行出错:", str(e))
finally:
    driver.quit()
  • 异常捕获:打印任何运行时错误

  • 资源清理:确保浏览器最终关闭

典型执行流程

  1. 打开浏览器 → 导航到登录页

  2. 定位验证码 → 图像预处理 → OCR识别

  3. 自动填写账号/密码/验证码 → 点击登录

  4. 检查登录结果 → 输出页面源码或错误信息

  5. 无论成功与否都关闭浏览器

具体代码展示

python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
import pytesseract
import io
import time

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx")

# 等待页面加载
time.sleep(2)

try:
    # 获取验证码元素
    code_img = driver.find_element(By.ID, 'imgCode')

    # 将验证码截图保存到内存
    img_bytes = code_img.screenshot_as_png
    image = Image.open(io.BytesIO(img_bytes))

    # 图像预处理(提高识别率)
    image = image.convert('L')  # 灰度化
    # image = image.point(lambda x: 0 if x < 128 else 255, '1')  # 二值化(根据需要启用)

    # 识别验证码
    custom_config = r'--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    textcode = pytesseract.image_to_string(image, config=custom_config)
    textcode = textcode.strip().replace(' ', '')[:4]  # 清理结果并取前4位
    print("识别的验证码:", textcode)

    if len(textcode) == 4:
        # 填写登录信息
        driver.find_element(By.ID, 'email').send_keys("2833622025@qq.com")
        driver.find_element(By.ID, 'pwd').send_keys("ckn12138")
        driver.find_element(By.ID, 'code').send_keys(textcode)
        driver.find_element(By.ID, 'denglu').click()

        # 等待登录完成
        time.sleep(3)

        # 验证登录是否成功
        if "退出登录" in driver.page_source:
            print("登录成功!")
            # 获取登录后的页面内容
            html = driver.page_source
            print(html)
        else:
            print("登录失败,请检查账号或验证码!")
    else:
        print("验证码识别失败或长度不正确")

except Exception as e:
    print("程序运行出错:", str(e))

finally:
    # 关闭浏览器
    driver.quit()

但是这个代码识别出来的验证码不准确 最好用超级鹰识别方式再识别一遍~

运行结果:

会自己填充账号密码之后

之后关闭浏览器

识别成功运行结果 因为验证码形式简单 比较好识别:

识别失败:

网页会显示验证码错误!

相关推荐
数据智能老司机5 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机6 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机6 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机6 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i6 小时前
drf初步梳理
python·django
每日AI新事件6 小时前
python的异步函数
python
这里有鱼汤7 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook16 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室17 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三18 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试