SoFunction
Updated on 2024-10-28

python3 get url file size sample code

In python3, urllib2 is replaced, so the header files add the

import  as urllib2
def getRemoteFileSize(url, proxy=None):
 """ Get remote file size via content-length header
  url - destination file URL
  proxy - proxy """
 opener = urllib2.build_opener()
 if proxy:
  if ().startswith('https://'):
   opener.add_handler(({'https' : proxy}))
  else:
   opener.add_handler(({'http' : proxy}))
 try:
  request = (url)
  request.get_method = lambda: 'HEAD'
  response = (request)
  ()
 except Exception:
  return 0
 else:
  print()
  fileSize = dict().get('content-length', 0)
  return int(fileSize)

Using the above code found that the output is 0, considering that it should not query the content-length field, print the field, found that the content-length field should be changed to Content-Length, change the normal

在这里插入图片描述

def getRemoteFileSize(url, proxy=None):
 """ Get remote file size via content-length header
  url - destination file URL
  proxy - proxy """
 opener = urllib2.build_opener()
 if proxy:
  if ().startswith('https://'):
   opener.add_handler(({'https' : proxy}))
  else:
   opener.add_handler(({'http' : proxy}))
 try:
  request = (url)
  request.get_method = lambda: 'HEAD'
  response = (request)
  ()
 except Exception:
  return 0
 else:
  print()
  fileSize = dict().get('Content-Length', 0)
  return int(fileSize)

summarize

The above is a small introduction to the python3 get url file size sample code, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!