python3获取url文件大小示例代码

yipeiwu_com7年前Python基础

在python3中,urllib2被替换为urllib.requeset,因此头文件中添加

import urllib.request as urllib2
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:
   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:
  return 0
 else:
  print(response.headers)
  fileSize = dict(response.headers).get('content-length', 0)
  return int(fileSize)

使用上段代码发现输出为0,考虑应该是没查询到content-length字段,打印response.headers字段后,发现content-length字段应改为Content-Length,改后正常

在这里插入图片描述

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:
   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:
  return 0
 else:
  print(response.headers)
  fileSize = dict(response.headers).get('Content-Length', 0)
  return int(fileSize)

总结

以上所述是小编给大家介绍的python3获取url文件大小示例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Pytorch 实现计算分类器准确率(总分类及子分类)

分类器平均准确率计算: correct = torch.zeros(1).squeeze().cuda() total = torch.zeros(1).squeeze().cuda...

在python中实现对list求和及求积

如下所示: # the basic way s = 0 for x in range(10): s += x # the right way s = sum(range(10))...

解决python写入带有中文的字符到文件错误的问题

在python写脚本过程中需要将带有中文的字符串内容写入文件,出现了报错的现象。 ---------------------------- UnicodeEncodeError: 'as...

flask的orm框架SQLAlchemy查询实现解析

这篇文章主要介绍了flask的orm框架SQLAlchemy查询实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一对多,多对多...

django 2.0更新的10条注意事项总结

前言 备受期待的django 2.0已经发布了,最大的一个变化就是不再支持python2.x版本了,这也为我们还在保守使用的2.x的同学们敲响了警钟,赶紧学习python3.x吧,虽然大...