使用requests配合urllib3的重试机制是提高爬虫稳定性的常见方法,通过配置HTTPAdapter实现自动重试。示例中定义create_session_with_retry函数,利用Retry类设置总重试次数、触发重试的状态码列表、允许重试的请求方法及退避因子。tenacity库提供更灵活的重试控制,支持任意函数的指数退避重试,适用于复杂场景。对于简单需求,可手动结合try-except与循环实现重试逻辑,便于调试。生产环境推荐使用requests+urllib3组合,合理设置重试参数以避免对服务器造成压力。

爬虫在请求网页时,常会遇到网络波动、目标服务器响应慢或临时封禁等问题。为提高稳定性,加入异常重试机制非常必要。Python中可通过多种方式实现请求失败后的自动重试。
requests库底层依赖urllib3,可以通过配置HTTPAdapter来启用连接重试功能。这是最常见且稳定的方法。
以下是一个设置请求重试的示例:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
<p>def create_session_with_retry(retries=3, backoff_factor=0.5):
session = requests.Session()
retry_strategy = Retry(
total=retries, # 总重试次数(包含首次请求)
status_forcelist=[429, 500, 502, 503, 504], # 遇到这些状态码时重试
method_whitelist=["GET", "POST"], # 允许重试的请求方法
backoff_factor=backoff_factor # 重试间隔时间增量
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session</p><h1>使用示例</h1><p>session = create_session_with_retry(retries=3)
try:
response = session.get("<a href="https://www.php.cn/link/874b2add857bd9bcc60635a51eb2b697">https://www.php.cn/link/874b2add857bd9bcc60635a51eb2b697</a>")
print(response.status_code)
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")</p>说明:
立即学习“Python免费学习笔记(深入)”;
tenacity是一个更灵活的Python重试库,支持任意函数的重试,不限于网络请求。
from tenacity import retry, stop_after_attempt, wait_exponential
import requests
<p>@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10))
def fetch_url(url):
print(f"正在请求: {url}")
response = requests.get(url, timeout=5)
response.raise_for_status()
return response</p><h1>调用</h1><p>try:
res = fetch_url("<a href="https://www.php.cn/link/874b2add857bd9bcc60635a51eb2b697">https://www.php.cn/link/874b2add857bd9bcc60635a51eb2b697</a>")
print(res.status_code)
except requests.exceptions.RequestException as e:
print(f"最终失败: {e}")</p>特点:
对于简单场景,可以直接使用try-except加循环实现重试逻辑。
import requests
import time
<p>def get_with_retry(url, max_retries=3, delay=1):
for i in range(max_retries):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return response
else:
print(f"状态码异常: {response.status_code},第{i+1}次尝试")
except requests.exceptions.RequestException as e:
print(f"请求出错: {e},第{i+1}次尝试")</p><pre class='brush:python;toolbar:false;'> if i < max_retries - 1:
time.sleep(delay * (2 ** i)) # 指数等待
return Noneresp = get_with_retry("https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635") if resp: print("请求成功") else: print("最终失败")
这种方法便于调试和自定义逻辑,适合小型项目或学习用途。
基本上就这些。根据项目复杂度选择合适的重试方案,推荐生产环境使用requests+urllib3组合,兼顾性能与可控性。重试机制虽好,也要注意设置合理次数和间隔,避免对目标服务器造成压力。
以上就是Python爬虫怎样使用异常重试机制_Python爬虫请求失败自动重试的设置方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号