本文介绍了几种常用的python下载文件的方法,具体使用到了htttplib2,urllib等包,希望对大家有帮忙。
1.简单文件下载
使用htttplib2,具体代码如下:
h = httplib2.Http()
url = 'https://www.jb51.net/ip.zip'
resp, content = h.request(url)
if resp['status'] == '200':
with open(filename, 'wb') as f:
f.write(content)
使用urllib,具体代码如下:
filename = urllib.unquote(url).decode('utf8').split('/')[-1]
urllib.urlretrieve(url, filename)
2.较大文件下载
def down_file():
url = "https://www.jb51.net/download.abc"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
file_size_dl = 0
block_sz = 8192
while True: