python2.7中关于下载文件的一个判断
per=100.0*count*size/total_filesize
filesize = total_filesize
if per>100:
per=100
print '\rFileSize: %d Already download %d KB(%.2f ' %(filesize,count*size/1024,per)+'%)' python
[解决办法]
可以通过发送“HEAD request”,即告诉server我只想要header,然后读取其中的content-length属性。注意有的网站返回的header没有这个属性。(主要引自http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python)。
In [301]: import urllib2
In [302]: class HeadRequest(urllib2.Request):
...: def get_method(self):
...: return "HEAD"
In [303]: def getResourceLength(url):
...: response = urllib2.urlopen(HeadRequest(url))
...: return response.info().getheader('Content-Length')
...:
In [304]: getResourceLength("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
Out[304]: '5510872'
In [305]: getResourceLength("http://www.google.com/index.html") # 没有文件长度时会返回None