【问题标题】:define timeout in web request with python用python在web请求中定义超时
【发布时间】:2019-08-07 16:33:43
【问题描述】:

这是我的场景。我正在向在某些情况下花费太长时间的网页发出请求。我希望当超过 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)

出于保密原因,我没有放真实的网址,但通常不设置超时,它可以工作

【问题讨论】:

    标签: python exception python-requests timeout connection-timeout


    【解决方案1】:

    使用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")
    

    【讨论】:

    • @yavg,如果这个问题对你有帮助,请考虑支持并接受它。谢谢:)
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多