代码如下:
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, e: # 远程文件不存在 return 0 else: filesize = dict(response.headers).get(‘content-length’, 0) return int(filesize)