使用ddddocr(解析验证码)

该文章演示了一个使用Python进行OCR验证码识别的流程,涉及ddddocr库的安装与使用。首先,通过pip安装ddddocr,然后导入并使用该库读取和识别图像中的验证码。接着,文章展示了在爬虫登录场景中如何获取和处理验证码,利用BeautifulSoup解析HTML获取验证码图片URL,下载图片并使用ddddocr进行识别。最后,将识别后的验证码用于模拟登录请求。
摘要由CSDN通过智能技术生成

简介
硬性要求

python >= 3.8

安装

pip install ddddocr

使用

import ddddocr
import requests

def get_code(path):
    ocr = ddddocr.DdddOcr()
    with open(path, 'rb') as f:
        img_bytes = f.read()
    res = ocr.classification(img_bytes)
    print('识别出的验证码为:' + res)
    return res

# captcha_image = requests.get("https://scsso.zhjpec.edu.cn/authserver/app/validate/genCode?code=0.8384928333969981")
# with open('captcha.png', 'wb') as f:
#     f.write(captcha_image.content)
# get_code('captcha.png')

爬虫中的使用

#pip install beautifulsoup4
#pip install requests

import requests
from bs4 import BeautifulSoup
from code import get_code

# Define the login URL and payload
login_url = 'https://scsso.zhjpec.edu.cn/authserver/login?'
payload = {
    'username': 'your_username',
    'password': 'your_password',
    'captcha': 'captcha_code'
}

headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
}

# Send a GET request to the login page to obtain the captcha image
login_page = requests.get(login_url,headers=headers)
soup = BeautifulSoup(login_page.content, 'html.parser')
captcha_image_url = "https://scsso.zhjpec.edu.cn" + soup.find('img', {'class': 'mvLoginForm-bottom-img'})['src']
# Use a library like pytesseract to extract the captcha code from the image
captcha_image = requests.get(captcha_image_url)
with open('captcha.png', 'wb') as f:
    f.write(captcha_image.content)
captcha_code = get_code('captcha.png')
print('dd', captcha_code)
# Add the captcha code to the payload and send a POST request to the login page
payload['captcha'] = captcha_code

response = requests.post(login_url, data=payload)

# Check if the login was successful
if 'Welcome' in response.text:
    print('Login successful!')
else:
    print('Login failed. Please check your credentials and try again.')

GitHub
文档地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值