Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python请求错误处理_Python_Python Requests - Fatal编程技术网

python请求错误处理

python请求错误处理,python,python-requests,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

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

您希望处理异常
请求。异常。ConnectionError
,如下所示:

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

您希望处理异常
请求。异常。ConnectionError
,如下所示:

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

捕获
连接错误时,您可能需要设置适当的超时:

url = "http://www.stackoverflow.com"

try:
    req = requests.get(url, timeout=2)  #2 seconds timeout
except requests.exceptions.ConnectionError as e:
    # Couldn't connect

查看是否要更改重试次数。

捕获连接错误时,可能需要设置适当的超时:

url = "http://www.stackoverflow.com"

try:
    req = requests.get(url, timeout=2)  #2 seconds timeout
except requests.exceptions.ConnectionError as e:
    # Couldn't connect

查看是否要更改重试次数。

如果我想捕获所有异常,而不仅仅是connectionerror,我可以在except之后删除这些内容吗?谢谢你的快速回答;但是,一般来说,我更喜欢以不同的方式处理不同类别的异常,因此您可能需要仔细考虑如何应用该逻辑。如果我想捕获所有异常,而不仅仅是connectionerror,我可以在exception之后删除这些内容吗?谢谢你的快速回答;但是,一般来说,我更喜欢以不同的方式处理不同的异常类,所以您可能需要仔细考虑如何应用该逻辑。