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)
相关推荐
许思王7 分钟前
【Python】组合数据类型:序列,列表,元组,字典,集合
开发语言·人工智能·python
程序员的开发手册1 小时前
新手教学系列——慎用Flask-SQLAlchemy慢日志记录
数据库·python·flask·sqlalchemy
木觞清3 小时前
Django学习第三天
python·学习·django
电饭叔3 小时前
《python程序语言设计》2018版第5章第52题利用turtle绘制sin函数
开发语言·python
YCCX_XFF214 小时前
ImportError: DLL load failed while importing _imaging: 操作系统无法运行 %1
开发语言·python
FutureUniant6 小时前
GitHub每日最火火火项目(7.7)
python·计算机视觉·ai·github·视频
杰哥在此6 小时前
Java面试题:讨论持续集成/持续部署的重要性,并描述如何在项目中实施CI/CD流程
java·开发语言·python·面试·编程
PY1787 小时前
Python的上下文管理器
数据库·python·oracle
Struggle to dream8 小时前
Python编译器的选择
开发语言·python
爱看书的小沐8 小时前
ASCII码对照表(Matplotlib颜色对照表)
python·matplotlib·rgb·ascii·colormap·颜色对照表·颜色映射