分享一个Python获取远程文件大小的函数代码,简单实用,是学习python编程的基础实例。
代码:
def getRemoteFileSize(url, proxy=None):
""" 通过content-length头获取远程文件大小
url - 目标文件URL
proxy - 代理 """
opener = urllib2.build_opener()
if proxy:
if url.lower().startswith(‘https://‘):
opener.add_handler(urllib2.ProxyHandler({‘https‘ : proxy}))
else: www.jbxue.com
opener.add_handler(urllib2.ProxyHandler({‘http‘ : proxy}))
try:
request = urllib2.Request(url)
request.get_method = lambda: ‘HEAD‘
response = opener.open(request)
response.read()
except Exception, e: # 远程文件不存在
return 0
else:
fileSize = dict(response.headers).get(‘content-length‘, 0)
return int(fileSize)
时间: 2024-11-05 06:52:00