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 flask解析json数据不完整的解决方法

当使用Python的flask框架来开发网站后台,解析前端Post来的数据,通常都会使用request.form来获取前端传过来的数据,但是如果传过来的数据比较复杂,其中右array,而...

Python从使用线程到使用async/await的深入讲解

前言 为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。 请注意,async和await是针对cor...

pytorch中tensor张量数据类型的转化方式

1.tensor张量与numpy相互转换 tensor ----->numpy import torch a=torch.ones([2,5]) tensor([[1.,...

从零学Python之hello world

简单的‘Hello World!' Python命令行 假设你已经安装好了Python, 那么在Linux命令行输入: 复制代码 代码如下:$python 将直接进入python。然后在...

pycharm下查看python的变量类型和变量内容的方法

pycharm下查看python的变量类型和变量内容的方法

用过Matlab的同学基本都知道,程序里面的变量内容可以很方便的查看到,但python确没这么方便,对于做数据处理的很不方便,其实不是没有这个功能,只是没有发现而已,今天整理一下供大家相...