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无法识别验证码,会返回空结果,这个时候就得刷新验证码或者刷新网页再次尝试登录了

相关推荐
你板子冒烟了3 小时前
JJJ:SD 卡中的 OCR(Operating Conditions Register)寄存器
ocr
扶尔魔ocy3 小时前
python程序打包成win的exe应用(以OCR应用为例)
python·ocr·中文识别
rannn_11120 小时前
【学以致用|python自动化办公】OCR批量识别自动存为Excel(批量识别发票)
python·ocr·excel·财务
momo_al1 天前
Umi-OCR制作双层PDF
pdf·ocr
余俊晖2 天前
多模态大模型OCR幻觉缓解思路:DianJin-OCR-R1通过“再看一眼”图像减轻幻觉
人工智能·ocr
AI人工智能+2 天前
药品经营许可证识别技术:通过深度学习算法实现资质文件的自动化识别与核验
人工智能·深度学习·ocr·药品经营许可证识别
xingxing_F3 天前
Initiater for mac 小巧的菜单栏OCR工具
macos·ocr
OpenBayes3 天前
教程上新|重新定义下一代 OCR:IBM 最新开源 Granite-docling-258M,实现端到端的「结构+内容」统一理解
人工智能·深度学习·机器学习·自然语言处理·ocr·图像识别·文档处理
旗讯数字4 天前
旗讯 OCR:破解全行业表格处理痛点,让数据从 “识别” 到 “可用” 一步到位
ocr·表格识别·结构化数据
AI人工智能+5 天前
发票识别技术:结合OCR与AI技术,实现纸质票据高效数字化,推动企业智能化转型
人工智能·nlp·ocr·发票识别