python爬虫网页崩溃怎么处理_《Python网络爬虫》1.2 爬取网页的异常处理
时间: 2023-07-19 16:51:09 浏览: 47
当Python爬虫在爬取网页时,可能会遇到各种异常情况,例如网络连接中断、页面不存在、请求超时等等。对于这些异常情况,我们需要进行相应的处理,以保证爬虫程序的健壮性和稳定性。
下面是《Python网络爬虫》中提到的一些常见的爬取网页的异常处理方法:
1. 使用try-except语句捕获异常,并进行相应的处理。例如:
```
import requests
try:
response = requests.get(url)
response.raise_for_status() # 如果响应状态码不是200,会抛出HTTPError异常
except requests.exceptions.RequestException as e:
print(e)
```
2. 设置超时时间,防止请求一直等待响应而导致程序崩溃。例如:
```
import requests
try:
response = requests.get(url, timeout=10) # 设置超时时间为10秒
response.raise_for_status()
except requests.exceptions.Timeout:
print('请求超时')
except requests.exceptions.RequestException as e:
print(e)
```
3. 使用代理IP或者用户代理(User-Agent)进行反反爬虫。例如:
```
import requests
proxies = {
'http': 'http://127.0.0.1:8888', # 设置代理IP
'https': 'http://127.0.0.1:8888'
}
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'
}
try:
response = requests.get(url, proxies=proxies, headers=headers)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
```
以上是一些常见的爬取网页的异常处理方法,可以根据实际情况进行选择和使用。