答案:编写健壮的Python爬虫需结合异常处理、重试机制与日志记录。首先捕获requests和解析库常见异常,如RequestException、Timeout、ConnectionError、HTTPError及AttributeError;通过try-except结构包裹请求与解析逻辑,并设置重试策略应对临时故障;推荐使用tenacity库实现带间隔的自动重试;生产环境中应采用logging模块记录错误详情,便于排查;同时通过设置请求头、控制频率、使用with语句和字段校验等预防措施提升稳定性。最终目标是让爬虫在出错时能优雅恢复而非崩溃。

在编写Python爬虫时,网络请求和数据解析过程容易受到各种外部因素影响,比如网络不稳定、目标网站结构变化、反爬机制触发等。因此,合理的异常处理机制是保证爬虫稳定运行的关键。
爬虫中最常见的异常主要来自网络请求库(如requests)和HTML解析库(如BeautifulSoup、lxml)。以下是几种典型异常及其处理方式:
示例代码:
使用try-except结构对请求和解析过程进行包裹:
立即学习“Python免费学习笔记(深入)”;
import requests
from bs4 import BeautifulSoup
import time
<p>def fetch_page(url, retries=3):
for i in range(retries):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # 触发HTTPError(如4xx/5xx)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.select_one('h1').text
return title
except requests.exceptions.Timeout:
print(f"请求超时,第{i+1}次重试...")
time.sleep(2)
except requests.exceptions.ConnectionError:
print("连接失败,检查网络或URL")
break
except requests.exceptions.RequestException as e:
print(f"请求发生未知错误: {e}")
break
except AttributeError:
print("页面结构改变,未找到指定元素")
break
return None
对于临时性故障(如短暂超时、限流),简单的重试策略能显著提高成功率。除了手动循环重试,也可以借助第三方库如tenacity实现更灵活的控制。
安装tenacity:pip install tenacity
使用装饰器自动重试:
from tenacity import retry, stop_after_attempt, wait_fixed <p>@retry(stop=stop_after_attempt(3), wait=wait_fixed(2)) def get_data_with_retry(url): response = requests.get(url, timeout=5) response.raise_for_status() return response.json()
上述代码表示最多尝试3次,每次间隔2秒,适用于API接口类爬取任务。
生产级爬虫应避免仅用print输出错误信息,而应使用logging模块记录异常详情,便于后期排查问题。
import logging
<p>logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("spider.log"),
logging.StreamHandler()
]
)</p><p>try:
result = fetch_page("<a href="https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635">https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635</a>")
except Exception as e:
logging.error(f"抓取失败: {url}, 错误: {e}", exc_info=True)
exc_info=True可记录完整的堆栈信息,有助于定位深层问题。
除被动捕获异常外,还应主动规避风险:
基本上就这些。一个健壮的爬虫不是不报错,而是能优雅地面对错误并做出合适反应。合理运用try-except、重试机制和日志系统,可以让爬虫在复杂环境中持续可靠运行。
以上就是Python爬虫怎样实现异常处理_Python爬虫运行中异常捕获与错误处理机制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号