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("[email protected]")
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("[email protected]")
        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()

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

运行结果:

会自己填充账号密码之后

之后关闭浏览器

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

识别失败:

网页会显示验证码错误!

相关推荐
不会飞的鲨鱼15 分钟前
【QQ音乐】sign签名| data参数加密 | AES-GCM加密 | webpack (下)
javascript·爬虫·python·webpack
放飞自我的Coder28 分钟前
【maker-pdf 文档文字识别(包含ocr),安装使用完整教程】
python·ocr·marker-pdf
zhonghuagongren1 小时前
高考加油!UI界面生成器!
python·学习·ui·高考
lkx097881 小时前
爬虫--以爬取小说为例
爬虫·python
哈哈哈哈哈哈哈哈哈...........3 小时前
【软件】在 macOS 上安装 Postman
测试工具·macos·postman
mizuhokaga3 小时前
Postman 发送 SOAP 请求步骤 归档
测试工具·postman
struggle20258 小时前
OramaCore 是您 AI 项目、答案引擎、副驾驶和搜索所需的 AI 运行时。它包括一个成熟的全文搜索引擎、矢量数据库、LLM界面和更多实用程序
人工智能·python·rust
chicpopoo9 小时前
Python打卡DAY40
人工智能·python·机器学习
waterHBO9 小时前
改进自己的图片 app
python
机器人梦想家10 小时前
【ROS2实体机械臂驱动】rokae xCoreSDK Python测试使用
python