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)
相关推荐
代码山河5 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
在世修行5 小时前
智学文枢:题目流水线
python·多线程·状态机·pyside
梯度下降者5 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
“AI国潮设计-小江”7 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
benchmark_cc8 小时前
用 Python 拉 A 股全市场实时快照:Notebook 请求、结果校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
伞伞悦读8 小时前
【第70期】Adam二阶矩不是方差:偏差校正、动量与AdamW完整实验
python
外收内放8 小时前
Python基础语法练习题(73)
java·前端·python
锋行天下9 小时前
Langgraph HITL 中断运行,用户输入后输出打字效果
人工智能·python
时早玖沐9 小时前
给 AstrBot 写一个天气推送插件:12 次提交、6 个坑
python·开源·ai编程
触底反弹9 小时前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi