Python urllib的urlretrieve()函数解析Python的爬虫函数

来源:互联网 发布:mamp mysql 启动失败 编辑:程序博客网 时间:2024/05/06 07:22

下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。

1>>> help(urllib.urlretrieve)
2Help on function urlretrieve in module urllib:
3 
4urlretrieve(url, filename=None, reporthook=None, data=None)
  • 参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
  • 参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
  • 参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。

下面通过例子来演示一下这个方法的使用,这个例子将 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同时显示下载的进度。

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

在 Python Shell 里执行如下:

01Python 2.7.5 (default, May 15 201322:44:16) [MSC v.1500 64 bit (AMD64)] on win32
02Type "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 * * / 
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
03import urllib
04import os
05def Schedule(a,b,c):
06    '''''
07    a:已经下载的数据块
08    b:数据块的大小
09    c:远程文件的大小
10   '''
11    per = 100.0 * * / c
12    if per > 100 :
13        per = 100
14    print '%.2f%%' % per
15url = 'http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2'
16#local = url.split('/')[-1]
17local = os.path.join('/data/software','Python-2.7.5.tar.bz2')
18urllib.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(代理的方式)连接,如果远程数据量过大,单线程下载太慢的话可以采用多线程下载,这个就是传说中的爬虫。

阅读全文
0 0
原创粉丝点击