使用 python 在 Web 请求中定义超时
define timeout in web request with python
这是我的场景。我正在向某个网页发出请求,该网页在某些情况下花费的时间过长。我希望当超过 10 秒没有从服务器发出响应时,请求被取消但没有收到任何错误。
这是我当前的代码和出现在我身上的错误。出现此错误时,我的代码结束。
总之我想发出一个网络请求并限制如果在 10 秒内没有答案,我完成请求并继续我的代码。
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
.
.
.
当 10 秒过去时,我收到此错误
ReadTimeout: HTTPConnectionPool(host='www.webpage.com', port=80): Read timed out. (read timeout=10)
出于保密原因,我没有放真正的url,但通常不设置超时,它可以工作
使用exception
处理超时
try:
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
except requests.exceptions.ReadTimeout:
print("Server didn't respond within 10 seconds")
这是我的场景。我正在向某个网页发出请求,该网页在某些情况下花费的时间过长。我希望当超过 10 秒没有从服务器发出响应时,请求被取消但没有收到任何错误。 这是我当前的代码和出现在我身上的错误。出现此错误时,我的代码结束。 总之我想发出一个网络请求并限制如果在 10 秒内没有答案,我完成请求并继续我的代码。
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
.
.
.
当 10 秒过去时,我收到此错误
ReadTimeout: HTTPConnectionPool(host='www.webpage.com', port=80): Read timed out. (read timeout=10)
出于保密原因,我没有放真正的url,但通常不设置超时,它可以工作
使用exception
处理超时
try:
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
except requests.exceptions.ReadTimeout:
print("Server didn't respond within 10 seconds")