Python实现HTTP协议下的文件下载方法总结

yipeiwu_com6年前Python基础

本文介绍了几种常用的python下载文件的方法,具体使用到了htttplib2,urllib等包,希望对大家有帮忙。

1.简单文件下载

使用htttplib2,具体代码如下:

h = httplib2.Http()      
url = '//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 = "//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:  
    buffer = u.read(block_sz)  
    if not buffer:  
      break  
    
    file_size_dl += len(buffer)  
    f.write(buffer)  
  f.close()  

在获取下载文件名的过程中,可以解析url,代码如下:

scheme, netloc, path, query, fragment = urlparse.urlsplit(url)  
filename = os.path.basename(path)  
if not filename:  
  filename = 'downloaded.file'  

3.端点续传下载
在使用HTTP协议进行下载的时候只需要在头上设置一下Range的范围就可以进行断点续传下载,当然,首先服务器需要支持断点续传。

利用Python的urllib2模块完成断点续传下载的例子:

#!/usr/bin/python 
# -*- coding: UTF-8 -* 
''' 
Created on 2013-04-15 
Created by RobinTang 
A demo for Resuming Transfer 
''' 
import urllib2 
 
req = urllib2.Request('http://www.python.org/') 
req.add_header('Range', 'bytes=0-20') # set the range, from 0byte to 19byte, 20bytes len 
res = urllib2.urlopen(req) 
 
data = res.read() 
 
print data 
print '---------' 
print 'len:%d'%len(data) 

相关文章

python 反向输出字符串的方法

python 反向输出字符串的方法 方法一:采用列表reversed函数 class Solution(object): def reverse_string(self, s):...

python中reader的next用法

python中有个csv包(build-in),该包有个reader,按行读取csv文件中的数据 reader.next()作用:打印csv文件中的第一行标题header (python...

tensorflow 获取所有variable或tensor的name示例

获取所有variable(每个op中可训练的张量)的name: for variable_name in tf.global_variables(): print(variabl...

浅谈numpy数组中冒号和负号的含义

在实际使用numpy时,我们常常会使用numpy数组的-1维度和”:”用以调用numpy数组中的元素。也经常因为数组的维度而感到困惑。 总体来说,”:”用以表示当前维度的所有子模块 “-...

Python中optparse模块使用浅析

Python中optparse模块使用浅析

最近遇到一个问题,是指定参数来运行某个特定的进程,这很类似Linux中一些命令的参数了,比如ls -a,为什么加上-a选项会响应。optparse模块实现的也是类似的功能,它是为脚本传递...