zoukankan      html  css  js  c++  java
  • Python-requests请求的超时时间

    python程序根据url从互联网上批量下载图片时,设置HTTP或Socket超时,来防止爬虫爬取某个页面时间过长,导致程序卡置不前。

    一种解决方案是全局设置:

    import socket
    socket.setdefaulttimeout(t)
    t:代表经过t秒后,如果还未下载成功,自动跳入下一次操作,此次下载失败

    另外一种解决方案是:

    使用timeout 参数可以设定等待连接的数,如果等待超时,Requests会抛出异常

    >>> requests.get('http://github.com', timeout=0.001)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
    >>> requests.get('https://www.baidu.com',timeout=0.5)
    <Response [200]>

    timeout 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)。

    第三种

    import time
    import requests
    from requests.adapters import HTTPAdapter
     
    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))
    s.mount('https://', HTTPAdapter(max_retries=3))
     
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    try:
      r = s.get('http://www.google.com.hk', timeout=5)
      return r.text
    except requests.exceptions.RequestException as e:
      print(e)
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    max_retries 为最大重试次数,重试3次,加上最初的一次请求,一共是4次,所以上述代码运行耗时是20秒而不是15秒
     
    第四种:捕获请求异常:
    def gethtml(url):
      i = 0
      while i < 3:
        try:
          html = requests.get(url, timeout=5).text
          return html
        except requests.exceptions.RequestException:
          i += 1

     

  • 相关阅读:
    杨辉三角实现
    三种方式都能生成同样的列表
    Python 直接赋值、浅拷贝和深度拷贝解析
    Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
    教你玩转CSS 分组选择器和嵌套选择器
    教你玩转CSS padding(填充)
    教你玩转CSS 轮廓(outline)属性
    教你玩转CSS margin(外边距)
    教你玩转CSS border(边框)
    教你玩转CSS表格(table)
  • 原文地址:https://www.cnblogs.com/zhaoyang110/p/12033921.html
Copyright © 2011-2022 走看看