python爬虫网页崩溃怎么处理_《Python网络爬虫》1.2 爬取网页的异常处理
时间: 2023-07-19 22:06:59 浏览: 41
当爬虫遇到网页崩溃时,通常会抛出异常。可以使用 Python 的异常处理机制来处理这些异常。以下是一些常见的处理方式:
1. 使用 try-except 语句捕获异常,避免程序崩溃:
```python
import requests
try:
response = requests.get(url)
# 处理响应内容
except Exception as e:
print(e)
```
2. 设置超时时间,避免程序无限等待:
```python
import requests
try:
response = requests.get(url, timeout=10)
# 处理响应内容
except requests.exceptions.Timeout as e:
print(e)
```
3. 使用重试机制,多次尝试访问网页:
```python
import requests
import time
def get_html(url):
for i in range(3): # 最多重试3次
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
except Exception as e:
print(e)
time.sleep(1) # 等待1秒钟后重试
return None
```
以上这些方法可以帮助我们应对网页崩溃的情况,保证爬虫的稳定性和可靠性。