在互联网数据采集领域,Python爬虫是一种强大的工具,能够帮助我们高效地获取网页数据。然而,在实际应用中,许多网站为了防止恶意爬取,会在检测到频繁请求时要求用户输入验证码。这无疑给爬虫的正常运行带来了挑战。本文将详细介绍Python爬虫在多次请求后被要求验证码时的应对策略,并提供具体的实现代码。
验证码(CAPTCHA)是一种区分用户是人类还是自动化程序的公共全自动程序。常见的验证码类型包括:
验证码的原理是利用人类视觉识别能力优于机器识别能力的特性,阻止自动化程序(如爬虫)的访问。当网站检测到短时间内多次请求时,会触发验证码机制,以确保后续操作是由真实用户完成。
降低请求频率是最简单直接的应对方式。通过合理控制爬虫的请求间隔,避免触发网站的反爬机制。
import time
def fetch_data(url):
response = requests.get(url)
return response
urls = ["http://example.com/page1", "http://example.com/page2", ...]
for url in urls:
data = fetch_data(url)
# 处理数据
time.sleep(2) # 每次请求间隔2秒
使用代理IP可以隐藏爬虫的真实IP地址,避免因IP被封导致的验证码问题。常见的代理IP获取方式包括使用免费代理池或付费代理服务。
import requests
def fetch_data_with_proxy(url, proxy):
proxies = {
"http": proxy,
"https": proxy
}
response = requests.get(url, proxies=proxies)
return response
proxy_list = ["http://192.168.1.1:8080", "http://192.168.1.2:8080", ...]
for proxy in proxy_list:
data = fetch_data_with_proxy("http://example.com", proxy)
# 处理数据
通过修改请求头中的User-Agent、Referer等字段,伪装成正常的浏览器请求,降低被识别为爬虫的风险。
import requests
def fetch_data_with_headers(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Referer": "http://example.com"
}
response = requests.get(url, headers=headers)
return response
data = fetch_data_with_headers("http://example.com")
# 处理数据
对于图片验证码,可以使用OCR(光学字符识别)技术进行识别。常见的OCR工具包括Tesseract和百度OCR等。
sudo apt-get install tesseract-ocr
。from PIL import Image
import pytesseract
import requests
from io import BytesIO
def recognize_captcha(image_url):
response = requests.get(image_url)
image = Image.open(BytesIO(response.content))
captcha_text = pytesseract.image_to_string(image)
return captcha_text
captcha_url = "http://example.com/captcha.jpg"
captcha_text = recognize_captcha(captcha_url)
print("识别的验证码:", captcha_text)
以下是一个综合应用上述策略的完整案例,爬取一个需要验证码的网站数据。
import requests
import time
import random
import pytesseract
from PIL import Image
from io import BytesIO
# 配置
captcha_url = "http://example.com/captcha.jpg"
target_url = "http://example.com/data"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Referer": "http://example.com"
}
# 代理信息
proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"
# 构造代理字典
proxies = {
"http": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}",
"https": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}"
}
def fetch_captcha():
# 使用代理请求验证码图片
response = requests.get(captcha_url, headers=headers, proxies=proxies)
image = Image.open(BytesIO(response.content))
captcha_text = pytesseract.image_to_string(image)
return captcha_text
def fetch_data_with_captcha(captcha_text):
data = {
"captcha": captcha_text
}
# 使用代理发送请求
response = requests.post(target_url, headers=headers, data=data, proxies=proxies)
return response
def main():
while True:
captcha_text = fetch_captcha()
response = fetch_data_with_captcha(captcha_text)
if response.status_code == 200:
print("数据获取成功:", response.text)
break
else:
print("验证码错误或请求失败,重新尝试...")
time.sleep(random.uniform(1, 3)) # 随机停留1到3秒
if __name__ == "__main__":
main()
在爬取需要验证码的网站时,降低请求频率、使用代理IP、伪装请求头、识别验证码以及模拟正常用户行为等策略可以有效应对验证码问题。通过合理组合这些策略,我们可以提高爬虫的稳定性和效率。然而,需要注意的是,爬虫的使用应遵循相关法律法规和网站的使用条款,避免对网站造成不必要的负担。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有