【Python】爬虫通过验证码

1、将验证码下载至本地

python 复制代码
# 获取验证码界面html
url = 'http://www.example.com/a.html'
resp = requests.get(url)
soup = BeautifulSoup(resp.content.decode('UTF-8'), 'html.parser')

#找到验证码图片标签,获取其地址
src = soup.select_one('div.captcha-row img')['src']

# 验证码下载至本地
resp = requests.get(src)
with open('../images/verify.png', 'wb') as f:
	f.write(resp.content)

2、解析验证码

powershell 复制代码
pip install ddddocr
python 复制代码
ocr = ddddocr.DdddOcr()
with open('../images/verify.png', 'rb') as f:
    img = f.read()
    code = ocr.classification(img)
    print(code)

3、发送验证码

python 复制代码
	#获取 token,一般验证码框有个隐藏的token
	token = soup.find('input', {'name': 'csrfToken'}).get('value')
	
	# 提交按钮对应的URL
	verify_url = 'https://www.example.com/verify'
	
	# 表单数据具体有哪几项可以在界面提交时查看(F12)
	data = {
	    'vcode': code,
	    'token': token,
	    'btnPost':''
	}
	
	# 请求头(F12 从请求里扒)
	headers = {
	    'content-type': 'application/x-www-form-urlencoded',
	    'user-agent': 'Mozilla/5.0 (Macintosh;) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'
	}
	
	response = requests.post(verify_url, data=data, headers=headers)
	
	if response.status_code == 200:
	    print('人机验证 - success')
	else:
	    print('人机验证 - fail')
相关推荐
每天吃的很好的Ruby24 分钟前
报错ValueError: sampler option is mutually exclusive with shuffle
人工智能·pytorch·python
清水白石00825 分钟前
Python 性能优化全景解析:当 Big O 骗了你——深挖常数开销、内存与解释器黑盒
开发语言·python·性能优化
oi..28 分钟前
python Get/Post请求练习
开发语言·经验分享·笔记·python·程序人生·安全·网络安全
速易达网络1 小时前
python地图商城可视化系统
python
@fai1 小时前
PyQt6 Graphic进阶实战:打造一个视觉恒定的可缩放矩形框
python·pyqt
luanma1509801 小时前
PHP vs C#:30字秒懂两大语言核心差异
android·开发语言·python·php·laravel
Channing Lewis1 小时前
Python 全局变量调用了一个函数,如何实现每次使用时都运行一次函数获取最新的结果
开发语言·python
浅墨cgz1 小时前
查找并删除源目录中与目标目录重复的文件
python
云姜.1 小时前
YAML简单使用
python
喵手1 小时前
Python爬虫实战:手把手教你Python 自动化构建志愿服务岗位结构化数据库!
爬虫·python·自动化·数据采集·爬虫实战·零基础python爬虫教学·志愿服务岗位结构数据库打造