python爬虫进阶-每日一学(GIF验证码识别)

目的

学习更多的python反爬虫策略

测试网址
bash 复制代码
http://credit.customs.gov.cn/ccppserver/verifyCode/creator

分析

bash 复制代码
01 下载gif图片
02 使用ddddocr逐帧识别
03 如指定字符串出现次数大于等于3,则认定为正确的识别结果
经验证,识别成功率95%+

源码

python3 复制代码
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2023/12/26 11:26
# @Author  : jia666666
# @FileName: 01 下载.py
import time
from PIL import Image
import ddddocr
import io
import requests

headers = {
	"Host": "credit.customs.gov.cn",
	"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
	"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
	"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
	"Accept-Encoding": "gzip, deflate",
	"Upgrade-Insecure-Requests": "1",
	"Connection": "keep-alive"
}


def get_yzm():
	while True:
		url = f"http://credit.customs.gov.cn/ccppserver/verifyCode/creator?{int(time.time() * 1000)}"
		response = requests.get(url, headers=headers, verify=False)
		
		#先保存本地在识别
		if savesign:
			with open(savepath, 'wb') as file:
				file.write(response.content)
			image = Image.open(savepath)
		else:
			#不保存本地
			image=Image.open(io.BytesIO(response.content))
		

		# 存储识别结果的字符串
		ocrresult = ''
		# 出现几次停止
		ocrcount = 3
		# 最后结果
		endres = ''
		
		i=0#开始帧
		while True:
			try:
				image.seek(i)
				ocr = ddddocr.DdddOcr()
				res = ocr.classification(image)
				ocrresult = ocrresult + res
				if len(res) == 4:
					if ocrresult.count(res) >= ocrcount:
						endres = res
						break
				if endres:
					break
				else:
					i=i+1
	
			except Exception as e:
				pass
				break
		if endres:
			return endres
#开始时间
start_time = time.time()
#gif是否保存本地
savesign=True
#保存本地的路径
savepath=r"yzm.gif"
print("gif识别结果",get_yzm())
print("用时", time.time() - start_time)
相关推荐
摆烂小白敲代码44 分钟前
腾讯云智能结构化OCR在物流行业的应用
大数据·人工智能·经验分享·ocr·腾讯云
nimadan121 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
yunhuibin3 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君4 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
秀儿还能再秀4 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh4 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
多恩Stone5 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
XW01059996 小时前
4-11判断素数
前端·python·算法·素数
深蓝电商API6 小时前
爬虫增量更新:基于时间戳与哈希去重
爬虫·python
两万五千个小时6 小时前
构建mini Claude Code:06 - Agent 如何「战略性遗忘」(上下文压缩)
人工智能·python