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)
相关推荐
橙露4 分钟前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化
Omigeq10 分钟前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
2301_8084143812 分钟前
自动化测试的实施
开发语言·python
无限码力16 分钟前
华为OD技术面真题 - Python开发 - 4
python·华为od·华为od技术面真题·华为od面试八股文·华为od面试真题·华为odpython开发真题·华为od技术面题目
l1t1 小时前
用wsl自带的python 3.10下载适用于3.12的pandas版本结合uv安装python 3.12模拟离线安装场景
python·pandas·uv
飞Link1 小时前
【AI大模型实战】万字长文肝透大语言模型(LLM):从底层原理解析到企业级Python项目落地
开发语言·人工智能·python·语言模型·自然语言处理
翻斗包菜1 小时前
第 03 章 Python 操作 MySQL 数据库实战全解
数据库·python·mysql
xcjbqd02 小时前
如何修改Oracle服务器默认的日期格式_NLS_DATE_FORMAT全局配置
jvm·数据库·python
white-persist2 小时前
【vulhub spring CVE-2018-1270】CVE-2018-1270 Spring Messaging 远程命令执行漏洞 完整复现详细分析解释
java·服务器·网络·数据库·后端·python·spring
EnCi Zheng2 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
开发语言·python