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实现栅栏加解密 支持密钥加密

栅栏加解密是对较短字符串的一种处理方式,给定行数Row,根据字符串长度计算出列数Column,构成一个方阵。 加密过程:就是按列依次从上到下对明文进行排列,然后按照密钥对各行进行打乱,最...

详解python中字典的循环遍历的两种方式

开发中经常会用到对于字典、列表等数据的循环遍历,但是python中对于字典的遍历对于很多初学者来讲非常陌生,今天就来讲一下python中字典的循环遍历的两种方式。 注意: python2...

python转换摩斯密码示例

复制代码 代码如下:CODE = {'A': '.-',     'B': '-...',   'C': '-.-.',&nb...

python实现单链表的方法示例

python实现单链表的方法示例

前言 首先说下线性表,线性表是一种最基本,最简单的数据结构,通俗点讲就是一维的存储数据的结构。 线性表分为顺序表和链接表: 顺序表示指的是用一组地址连续的存储单元依次存储线性表的数...

Python高级特性——详解多维数组切片(Slice)

(1) 我们先用arange函数创建一个数组并改变其维度,使之变成一个三维数组: >>> a = np.arange(24).reshape(2,3,4) >...