python下載文件的三種方法

Python開發中時長遇到要下載文件的狀況,最經常使用的方法就是經過Http利用urllib或者urllib2模塊。html

固然你也能夠利用ftplib從ftp站點下載文件。此外Python還提供了另一種方法requestspython

下面來看看三種方法是如何來下載zip文件的:
方法一:api

import urllib 
import urllib2 
import requests
print "downloading with urllib" 
url = 'http://***/test/demo.zip' 
print "downloading with urllib"
urllib.urlretrieve(url, "demo.zip")

 

方法二:函數

import urllib2
print "downloading with urllib2"
url = 'http://***/test/demo.zip' 
f = urllib2.urlopen(url) 
data = f.read() 
with open("demo2.zip", "wb") as code: 
code.write(data)

 


方法三:ui

import requests 
print "downloading with requests"
url = 'http://***/test/demo.zip' 
r = requests.get(url) 
with open("demo3.zip", "wb") as code:
code.write(r.content)

 

看起來使用urllib最爲簡單,一句語句便可。固然你能夠把urllib2縮寫成:url

f = urllib2.urlopen(url) 
with open("demo2.zip", "wb") as code:
code.write(f.read())

==========================================python requests======spa

在HTTP相關處理中使用python是沒必要要的麻煩,這包括urllib2模塊以巨大的複雜性代價獲取綜合性的功能。相比於urllib2,Kenneth Reitz的Requests模塊更能簡約的支持完整的簡單用例

簡單的例子:
想象下咱們試圖使用get方法從http://example.test/獲取資源而且查看返回代碼,content-type頭信息,還有response的主體內容。這件事不管使用urllib2 或者Requests都是很容易實現的。
urllib2:code

import urllib2

url = 'http://example.test/'
response = urllib2.urlopen(url)
response.getcode()
-- 200
response.headers.getheader('content-type')
-- 'text/html; charset=utf-8'
response.read()
-- 'Hello, world!'

 

Requests:htm

import requests

url = 'http://example.test/'
response = requests.get(url)
response.status_code
-- 200
response.headers['content-type']
-- 'text/html; charset=utf-8'
response.content
-- u'Hello, world!這兩種方法很類似,相對於urllib2調用方法讀取response中的屬性信息,Requests則是使用屬性名來獲取對應的屬性值。

二者還有兩個細微可是很重要的差異:
1. Requests 自動的把返回信息有Unicode解碼
2. Requests 自動保存了返回內容,因此你能夠讀取屢次,而不像urllib2.urlopen()那樣返回的只是一個相似文件類型只能讀取一次的對象。

第二點是在python交互式環境下操做代碼很使人討厭的事情

一個複雜一點的例子:如今讓咱們嘗試下複雜點得例子:使用GET方法獲取http://foo.test/secret的資源,此次須要基本的http驗證。使用上面的代碼做爲模板,好像咱們只要把urllib2.urlopen() 到requests.get()之間的代碼換成能夠發送username,password的請求就好了

這是urllib2的方法:對象

import urllib2

url = 'http://example.test/secret' 
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
password_manager.add_password(None, url, 'dan', 'h0tdish') 
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) 
opener = urllib2.build_opener(auth_handler) 
urllib2.install_opener(opener) 
response = urllib2.urlopen(url) 
response.getcode() 
-- 200 
response.read() 
-- 'Welcome to the secret page!' 


一個簡單的方法中實例化了2個類,而後組建了第三個類,最後還要裝載到全局的urllib2模塊中,最後才調用了urlopen,那麼那兩個複雜的類是什麼的
迷惑了嗎, 這裏全部urllib2的文檔 http://docs.python.org/release/2.7/library/urllib2.html
那Requests是怎麼樣解決一樣的問題的呢?

Requests:

import requests 
url = 'http://example.test/secret'
response = requests.get(url, auth=('dan', 'h0tdish'))
response.status_code
-- 200
response.content
-- u'Welcome to the secret page!'


只是在調用方法的時候增長了一個auth關鍵字函數
我敢打賭你不用查文檔也能記住。

錯誤處理 Error HandlingRequests 對錯誤的處理也是很很是方面。若是你使用了不正確的用戶名和密碼,urllib2會引起一個urllib2.URLError錯誤,然而Requests 會像你指望的那樣返回一個正常的response對象。只需查看response.ok的布爾值即可以知道是否登錄成功。

response = requests.get(url, auth=('dan', 'wrongPass'))
response.ok

-- False

其餘的一些特性:
* Requests對於HEAD, POST, PUT, PATCH, 和 DELETE方法的api一樣簡單
* 它能夠處理多部分上傳,一樣支持自動轉碼
* 文檔更好
* 還有更多

Requests 是很好的,下次須要使用HTTP時候能夠試試。

相關文章
相關標籤/搜索