python请求错误处理

标签 python python-requests

我正在编写一些小型 python 应用程序,它使用请求获取数据并将数据发布到 html 页面。

现在我遇到的问题是,如果我无法访问 html 页面,代码将停止并超过最大重试次数。如果无法连接到服务器,我希望能够做一些事情。

这样的事情可能吗?

这里是示例代码:

import requests

url = "http://127.0.0.1/"
req = requests.get(url)
if req.status_code == 304:
    #do something
elif req.status_code == 404:
    #do something else
# etc etc 

# code here if server can`t be reached for whatever reason

最佳答案

你想处理异常requests.exceptions.ConnectionError,像这样:

try:
    req = requests.get(url)
except requests.exceptions.ConnectionError as e:
    # Do stuff here

关于python请求错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23684298/

相关文章:

python - 使用我的 django 应用程序中另一个模块的模板文件夹

python - 如何使用 yml 文件重新创建我的 conda 环境?

python - json 对象中的 HTML 标记失败 HTTP POST 请求

python - 如何将更新后的页面内容传递给另一个函数?

python - 如何拆分带有参数的Python请求?

python - plotly fig 对象到 redis

python - 使用 3 个或更多参数输入字段调用函数 - function()()()

Python 从多个页面请求 .get()?

python - Flask - 在请求之间将值存储在内存中

python - C 和 Python 的接口(interface)