首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python2.7中关于下载文件的一个判断解决办法

2013-09-26 
python2.7中关于下载文件的一个判断per100.0*count*size/total_filesizefilesize total_filesizeif per

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

[解决办法]

刚用3.2的试了,urllib2没有,还得看看接口的变化

引用:
可以通过发送“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

热点排行