python图片识别(但是有时候识别不精准,有没有大佬帮忙解答):)

适合于selenium自动化测试对于图片验证码的识别

安装 Tesseract OCR:

首页 ·UB-曼海姆/tesseract Wiki

使用事列:

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

# 指定Tesseract OCR的可执行文件路径(根据实际安装路径修改)
# Windows系统示例
pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract-ocr\tesseract.exe'

# 1. 首先需要初始化WebDriver
driver = webdriver.Chrome()
try:
    # 2. 访问目标网页
    driver.get("https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx")

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

    # 3. 定位验证码元素
    captcha_element = driver.find_element(By.ID, "imgCode")
    captcha_screenshot = captcha_element.screenshot_as_png

    # 4. 使用OCR识别验证码
    image = Image.open(BytesIO(captcha_screenshot))
    # 保存验证码图片用于调试
    image.save("captcha.png")
    text = pytesseract.image_to_string(image).strip()
    print(f"识别出的验证码: {text}")

    # 5. 输入验证码
    # driver.find_element(By.ID, "captcha_input").send_keys(text)

    # 6. 其他登录操作...
    # driver.find_element(By.ID, "username").send_keys("your_username")
    # driver.find_element(By.ID, "password").send_keys("your_password")
    # driver.find_element(By.ID, "login-btn").click()

    # 保持浏览器打开查看结果
    input("按回车键退出...")
finally:
    # 确保浏览器最终会被关闭
    driver.quit()

完整登录古诗文网的例子:

python 复制代码
import pytesseract
from PIL import Image, ImageFilter, ImageEnhance
from io import BytesIO
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import cv2
import numpy as np

# Tesseract路径(根据自己的安装路径改)
pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract-ocr\tesseract.exe'


# 预处理函数
def preprocess(image):
    # 1. 转灰度
    gray = image.convert('L')
    # 2. 二值化
    threshold = 127
    gray = gray.point(lambda p: p > threshold and 255)
    # 3. 降噪
    gray = gray.filter(ImageFilter.MedianFilter())
    # 4. 增强对比度
    enhancer = ImageEnhance.Contrast(gray)
    gray = enhancer.enhance(2)
    return gray


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

    # 等待验证码加载
    captcha_element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, "imgCode"))
    )

    # 循环识别,直到成功(最多尝试3次)
    max_attempts = 3
    for attempt in range(max_attempts):
        # 截图验证码
        captcha_screenshot = captcha_element.screenshot_as_png
        image = Image.open(BytesIO(captcha_screenshot))

        # 预处理
        image = preprocess(image)

        # OCR识别(限定字符+模式)
        text = pytesseract.image_to_string(
            image,
            config="--psm 10 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        ).strip()

        # 验证长度(假设4位)
        if len(text) == 4:
            break
        else:
            # 识别失败,刷新验证码
            captcha_element.click()
            time.sleep(1)
            captcha_element = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.ID, "imgCode"))
            )

    # 填充登录信息
    driver.find_element(By.ID, "email").send_keys("用户名")
    driver.find_element(By.ID, "pwd").send_keys("密码")
    driver.find_element(By.ID, "code").send_keys(text)
    driver.find_element(By.ID, "denglu").click()
    # print(text)
    
    # 保持浏览器打开
    input("按回车键退出...")

finally:
    driver.quit()
相关推荐
做运维的阿瑞6 小时前
Linux 企业级备份体系实战:cron/anacron/restic/rclone 对比与脚本总结
linux·运维·服务器·后端·学习·系统架构·centos
gc_22996 小时前
学习Python中Selenium模块的基本用法(15:窗口操作)
python·selenium
keep_di8 小时前
06-django中配置接口文档coreapi
后端·python·django
NanXi_XZ9 小时前
kubernetes事件监控工具--Kube-Event
python·kubernetes
麦当_10 小时前
Cloudflare Workers 环境下的数据库死锁问题及解决方案
javascript·数据库·后端
java1234_小锋10 小时前
Scikit-learn Python机器学习 - 回归分析算法 - Lasso 回归 (Lasso Regression)
python·算法·机器学习
郑洁文10 小时前
上门代管宠物系统的设计与实现
java·spring boot·后端·毕业设计·毕设
倔强青铜三10 小时前
苦练Python第52天:一口气吃透Python的“七脉神剑”:生命周期+字符串魔术方法全解析
人工智能·python·面试
码事漫谈10 小时前
ReAct Agent:原理、应用与实战指南
后端