在Python中处理HTTP响应状态码(如200、404、500等)是Web开发中的常见任务。以下是关键处理方法和示例代码:
1. 使用 requests 库处理响应****
python
| import requests | |
|---|---|
| response = requests.get('example.com') | |
| # 直接检查状态码 | |
| if response.status_code == 200: | |
| print("请求成功") | |
| elif response.status_code == 404: | |
| print("页面未找到") | |
| elif response.status_code >= 500: | |
| print("服务器错误") | |
| # 更简洁的写法 | |
| response.raise_for_status() # 非200状态码会抛出异常 |
2. 使用 try-except 捕获异常****
python
| try: | |
|---|---|
| response = requests.get('example.com', timeout=5) | |
| response.raise_for_status() | |
| except requests.exceptions.HTTPError as err: | |
| if response.status_code == 404: | |
| print("资源不存在") | |
| elif response.status_code == 500: | |
| print("服务器崩溃") | |
| except requests.exceptions.RequestException: | |
| print("网络/连接错误") |
通过合理处理HTTP状态码,可以显著提升程序的健壮性和用户体验。