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()
相关推荐
诺斯贝克9 分钟前
Unable to create converter for xxx.NetworkResponse<Auth> for method AuthService
前端·后端
Trouville0111 分钟前
Python中encode和decode的用法详解
开发语言·python
用户693717500138411 分钟前
29.Kotlin 类型系统:智能转换:类型检查 (is) 与类型转换 (as)
android·后端·kotlin
用户693717500138412 分钟前
30. Kotlin 扩展:为“老类”添“新衣”:扩展函数与扩展属性
android·后端·kotlin
用户21903265273516 分钟前
Spring Boot 集成 Redis 实现看门狗 Lua 脚本分布式锁
java·后端
PFinal社区_南丞25 分钟前
Git 那些不太常用但非常实用的命令
后端
沸腾_罗强26 分钟前
GORM 软删除方案:使用 deleted_at 替代 is_deleted,用来支持表唯一索引创建
后端
belldeep27 分钟前
python:backtrader 使用指南
python·backtrader·量化回测
R.lin30 分钟前
Spring AI Alibaba 1.1 正式发布!
java·后端·spring
程序员阿明40 分钟前
spring security 6的知识点总结
java·后端·spring