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)
相关推荐
ZhengEnCi2 分钟前
AI Agent工具误调用怎么解决-从参数校验到高危二次确认的四层工程防线
python·llm·agent
镜子AI1 小时前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft
小oo呆2 小时前
【学习心得】Python协程
python
信誓旦旦的程序猿2 小时前
【Python量化实战宝典 #22】涨跌停、连板情绪手册:情绪指标构建(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
gCode Teacher 格码致知3 小时前
Pandas教学-21:subplots的使用
python·pandas·1024程序员节
2601_967980113 小时前
Python开发的顶级开源项目全景图:2025-2026年生态概览
python·机器学习·开源项目·数据科学·生态概览
benchmark_cc3 小时前
量化开发中,什么时候应该停止手动下载股票数据?
python·数据分析·pandas·量化交易·1024程序员节·股票数据·quantdash
泡茶喝茶写代码3 小时前
A股量化策略回测实战:从行情数据到绩效评估(第 15 篇):新高新低策略
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
全栈练习生4 小时前
Jev 决策模型
python·ai·1024程序员节
LMT流氓兔4 小时前
第五单元——第十二课:把脚本整理成项目
java·数据库·python·langchain·1024程序员节