Skip to main content
 首页 » 编程设计

python请求错误处理

2025年05月04日16rubylouvre

我正在编写一些小型 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