【py網頁】urllib.urlretrieve遠程下載


下面我們再來看看 urllib 模塊提供的 urlretrieve() 函數。urlretrieve() 方法直接將遠程數據下載到本地。

1 >>> help(urllib.urlretrieve)
2 Help on function urlretrieve in module urllib:
3  
4 urlretrieve(url, filename=None, reporthook=None, data=None)
  • 參數 finename 指定了保存本地路徑(如果參數未指定,urllib會生成一個臨時文件保存數據。)
  • 參數 reporthook 是一個回調函數,當連接上服務器、以及相應的數據塊傳輸完畢時會觸發該回調,我們可以利用這個回調函數來顯示當前的下載進度。
  • 參數 data 指 post 到服務器的數據,該方法返回一個包含兩個元素的(filename, headers)元組,filename 表示保存到本地的路徑,header 表示服務器的響應頭。

下面通過例子來演示一下這個方法的使用,這個例子將 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同時顯示下載的進度。

01 import urllib
02 def cbk(a, b, c): 
03     '''回調函數
04     @a: 已經下載的數據塊
05     @b: 數據塊的大小
06     @c: 遠程文件的大小
07     ''' 
08     per = 100.0 * a * b / 
09     if per > 100
10         per = 100 
11     print '%.2f%%' % per
12    
13 url = 'http://www.google.com'
14 local = 'd://google.html'
15 urllib.urlretrieve(url, local, cbk)

在 Python Shell 里執行如下:

01 Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
02 Type "copyright", "credits" or "license()" for more information.
03 >>> import urllib
04 >>> def cbk(a, b, c): 
05     '''回調函數
06     @a: 已經下載的數據塊
07     @b: 數據塊的大小
08     @c: 遠程文件的大小
09     ''' 
10     per = 100.0 * a * b / 
11     if per > 100
12         per = 100 
13     print '%.2f%%' % per
14  
15      
16 >>> url = 'http://www.google.com'
17 >>> local = 'd://google.html'
18 >>> urllib.urlretrieve(url, local, cbk)
19 -0.00%
20 -819200.00%
21 -1638400.00%
22 -2457600.00%
23 ('d://google.html', <httplib.HTTPMessage instance at 0x0000000003450608>)
24 >>>

下面是 urlretrieve() 下載文件實例,可以顯示下載進度。

01 #!/usr/bin/python
02 #encoding:utf-8
03 import urllib
04 import os
05 def Schedule(a,b,c):
06     '''''
07     a:已經下載的數據塊
08     b:數據塊的大小
09     c:遠程文件的大小
10    '''
11     per = 100.0 * a * b / c
12     if per > 100 :
13         per = 100
14     print '%.2f%%' % per
16 #local = url.split('/')[-1]
17 local = os.path.join('/data/software','Python-2.7.5.tar.bz2')
18 urllib.urlretrieve(url,local,Schedule)
19 ######output######
20 #0.00%
21 #0.07%
22 #0.13%
23 #0.20%
24 #....
25 #99.94%
26 #100.00%

通過上面的練習可以知道,urlopen() 可以輕松獲取遠端 html 頁面信息,然后通過 python 正則對所需要的數據進行分析,匹配出想要用的數據,在利用urlretrieve() 將數據下載到本地。對於訪問受限或者對連接數有限制的遠程 url 地址可以采用 proxies(代理的方式)連接,如果遠程數據量過大,單線程下載太慢的話可以采用多線程下載,這個就是傳說中的爬蟲。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM