如何下载小于1MB的文件?

时间:2019-10-08 03:49:48

标签: python

我正在尝试从给定的路径下载1MB pdf文件,但是我的代码存在问题。它的下载量超过1MB。我该如何解决?

try:
  response = requests.get(href, stream=True)
  total = response.headers.get('content-length')
  if len(total) > self.MAX_SIZE:
    print "maximum size (%d kbs)" % (self.MAX_SIZE/1024)
  else:
    if total is None:
      pass
    else:
       os.system('wget -P %s %s'%(PATH, href))
except Exception as e:
  pass

1 个答案:

答案 0 :(得分:0)

total = response.headers.get('content-length') 是代表您在比较之前应转换为数字的内容长度的字符串。

if int(total) > self.MAX_SIZE:

您的代码还有另一个问题,就是response = requests.get(href, stream=True)会降低性能-您在比较之前就下载了整个文件,如果这是唯一的话,应该使用response = requests.head(href)来检索Content-Length您需要。