【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')
相关推荐
ragnwang19 分钟前
Notes: Python pybind11 import C++ module
开发语言·c++·python
王中阳Go19 分钟前
后端转 Agent 岗面试怎么答:8 个高频问题与应答口径
人工智能·后端·python·大语言模型
weixin_307779131 小时前
RAG 面试陷阱——混合检索并非无条件优越:一个条件反转实验
人工智能·python·面试·职场和发展
云和数据.ChenGuang2 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
荣码4 小时前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
databook5 小时前
Pandas 与 Polars:语法、性能和资源占用方面的对比
python·数据分析·pandas
威哥爱编程5 小时前
Python 智能体开发实战 10:本地跑得好好的,一并发就崩?把它做成一个能上线的服务
python·agent
威哥爱编程5 小时前
Python 智能体开发实战 09:改了提示词,到底是变好还是变坏?搭一套能打分的离线评测
python·agent
meiying88386 小时前
多快递公司快递单号批量查询接口怎么对接?Python 聚合查询实现
java·大数据·python
Hello_Pyhx6 小时前
Deep-Live-Cam 源码配置思路:环境、模型与执行后端分开排查
python