使用ddddocr(解析验证码)
使用ddddocr(解析验证码)
·
简介
硬性要求
python >= 3.8
安装
pip install ddddocr
ddddocr1.2多版本的使用
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')
ddddocr1.5.5版本的使用
import ddddocr
import requests
def get_code(path):
ocr = ddddocr.DdddOcr(show_ad=False) # Added argument to suppress ads
with open(path, 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
print('识别出的验证码为:' + res)
return res
# To save and classify captcha image from the URL
def fetch_and_get_code(url, save_path):
captcha_image = requests.get(url)
with open(save_path, 'wb') as f:
f.write(captcha_image.content)
return get_code(save_path)
# Usage example
print(get_code("E:\\Daily_Work\\search\\JS\\JS_end\\captcha.png"))
# Or fetch and classify directly
# print(fetch_and_get_code("https://scsso.zhjpec.edu.cn/authserver/app/validate/genCode?code=0.8384928333969981", "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)