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()

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

运行结果:

会自己填充账号密码之后

之后关闭浏览器

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

识别失败:

网页会显示验证码错误!

相关推荐
Zhen (Evan) Wang5 分钟前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya9 分钟前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
赶紧去巡山35 分钟前
pyhton基础【23】面向对象进阶四
python
旷世奇才李先生1 小时前
PyCharm 安装使用教程
ide·python·pycharm
2501_924064111 小时前
2025年跨端云真机测试平台深度测评:XR与折叠屏时代的兼容性之战
测试工具·移动端自动化测试·自动化测试脚本
这里有鱼汤1 小时前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
尘浮7281 小时前
60天python训练计划----day59
开发语言·python
wh39332 小时前
使用Python将PDF转换成word、PPT
python·pdf·word
船长@Quant2 小时前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白
好开心啊没烦恼3 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas