Selenium自动填写验证码(偏小白版本OCR)

OCR基础示例

我直接

上代码

python 复制代码
from PIL import Image
import pytesseract

# 0 Orientation and script detection (OSD) only.
# 1 Automatic page segmentation with OSD.
# 2 Automatic page segmentation, but no OSD, or OCR.
# 3 Fully automatic page segmentation, but no OSD. (Default)
# 4 Assume a single column of text of variable sizes.
# 5 Assume a single uniform block of vertically aligned text.
# 6 Assume a single uniform block of text.
# 7 Treat the image as a single text line.
# 8 Treat the image as a single word.
# 9 Treat the image as a single word in a circle.
# 10 Treat the image as a single character.
# 11 Sparse text. Find as much text as possible in no particular order.
# 12 Sparse text with OSD.
# 13 Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific.


def get_chaptcha(psm):
    pytesseract.pytesseract.tesseract_cmd = r'D:\Tesseract-OCR\tesseract.exe'
    # 打开图像并转换为灰度图像
    image = Image.open('captcha.png').convert('L')
    # image = Image.open('captcha.png')
    # 使用 OCR 识别验证码
    captcha_text = pytesseract.image_to_string(image, config=f'--psm {psm}')
    print(captcha_text)
    return captcha_text


if __name__ == '__main__':
    get_chaptcha(1)

主要难点就是安装Tesseract-OCR了,去GItHub上搜一搜,去搜索引擎上搜一搜就能下载到了

然后就是使用tesseract_cmd 指定你的tesseract.exe的位置

Tesseract就是一个别人开发好的用来识别验证码的工具,下载好之后是为了给Python调用的

而pytesseract这个库就是为了调用Tesseract-OCR的

注意:OCR一共有13个模式,一般用索引为1的模式会比较通用,特别是像我这种小白,索引1的模式准没错

Selenium基础实战示例

python 复制代码
time.sleep(1)
captcha_png_tag = chrome.find_xpath('//*[@id="captchaImg"]')
# captcha_url = captcha_png_tag.get_attribute('src')
captcha_png_tag.screenshot('captcha.png')
time.sleep(1)
captcha_text = simple_ocr.get_chaptcha(1)
time.sleep(1)
print(captcha_text)
if captcha_text == "":
    login()

captcha_input_tag = chrome.find_xpath('//*[@id="captcha"]')
chrome.input_message_tag(captcha_text, captcha_input_tag)
  
time.sleep(2)
# 检查是否出现了验证码错误弹窗
if check_captcha_error(chrome.driver):
    close_all_alert(chrome.driver)
    chrome.driver.refresh()
    time.sleep(2)  # 等待2秒以确保页面已经加载
    login()

有的网站的验证码是动态验证码,不能用下载原图的方式获取验证码的图片

只能通过Selenium自带的截图功能截图保存,这个截图功能还是挺好用的,可以支持仅截图某个页面元素

注意:有时候OCR无法识别验证码,会返回空结果,这个时候就得刷新验证码或者刷新网页再次尝试登录了

相关推荐
EkihzniY11 小时前
OCR 赋能档案数字化:让沉睡的档案 “活” 起来
ocr
EkihzniY17 小时前
OCR 与 Agent:智能协作的 “黄金搭档”
ocr
xgc_java17 小时前
架构解密|一步步打造高可用的 JOCR OCR 识别服务
架构·ocr·状态模式
EkihzniY17 小时前
通用综合文字识别联动 MES 系统:OCR 是数据流通的核心
ocr
簪花走马过长安3 天前
【PDF识别改名】使用京东云OCR完成PDF图片识别改名,根据PDF图片内容批量改名详细步骤和解决方案
ui·pdf·ocr·excel·京东云·wps·图片区域识别重命名
ComPDFKit3 天前
为什么有些PDF无法复制文字?原理分析与解决方案
人工智能·pdf·ocr
EkihzniY4 天前
OCR 识别:车牌识别相机的 “火眼金睛”
数码相机·ocr
深度学习机器5 天前
OCRFlux-3B:开源 OCR + LLM 模型的新标杆,支持跨页表格合并
人工智能·机器学习·语言模型·ocr
AI人工智能+5 天前
应用药品经营许可证OCR,提升医药行业的信息化水平与监管效率
人工智能·ocr·文字识别
胡耀超5 天前
Umi-OCR 的 Docker安装(win制作镜像,Linux(Ubuntu Server 22.04)离线部署)
linux·深度学习·ubuntu·docker·容器·nlp·ocr