【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')
相关推荐
千寻girling3 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook7 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风8 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风8 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员