Python urllib模块提供了一个从指定的URL地址获取网页数据,然后对其进行分析处理,获取想要的数据。
1.查看urllib模块提供的urlopen函数。
1
2
3
|
help
(urllib.urlopen)
urlopen(url, data
=
None
, proxies
=
None
)
Create a
file
-
like
object
for
the specified URL to read
from
.
|
创建一个类文件对象为指定的url来读取。
参数url表示远程数据的路径,一般是http或者ftp路径。
参数data表示以get或者post方式提交到url的数据。
参数proxies表示用于代理的设置。
Python通过urlopen函数来获取html数据,下面通过函数getUrl()将百度首页显示到显示器上面。
1
2
3
4
5
6
7
|
#encoding:utf-8
import
urllib
def
getUrl(url):
page
=
urllib.urlopen(url)
html
=
page.read()
print
html
getUrl(
'http://www.baidu.com'
)
|
urlopen返回一个类文件对象,它提供了如下方法:
1)read() , readline() , readlines(),fileno()和close(): 这些方法的使用与文件对象完全一样。
2)info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息。
3)getcode():返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到。
4)geturl():返回请求的url地址。
urlopen方法实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/usr/bin/python
#encoding:utf-8
import
urllib
baidu
=
urllib.urlopen(
'http://www.baidu.com'
)
print
'http header:\n'
,baidu.info()
print
'http status:'
,baidu.getcode()
print
'url:'
,baidu.geturl()
for
line
in
baidu:
print
line,
baidu.close()
########output########
#http header:
#http status: 200
#url: http://www.baidu.com
#baidu home page
|
2.查看urllibe模块提供的urlretrieve函数。
1
2
|
help
(urllib.urlretrieve)
urlretrieve(url, filename
=
None
, reporthook
=
None
, data
=
None
)
|
urlretrieve方法直接将远程数据下载到本地。
参数finename指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
参数reporthook是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。
参数data指post到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename表示保存到本地的路径,header表示服务器的响应头。
urlretrieve方法下载文件实例,可以显示下载进度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/usr/bin/python
#encoding:utf-8
import
urllib
import
os
def
Schedule(a,b,c):
'''''
a:已经下载的数据块
b:数据块的大小
c:远程文件的大小
'''
per
=
100.0
*
a
*
b
/
c
if
per >
100
:
per
=
100
print
'%.2f%%'
%
per
url
=
'http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2'
#local = url.split('/')[-1]
local
=
os.path.join(
'/data/software'
,
'Python-2.7.5.tar.bz2'
)
urllib.urlretrieve(url,local,Schedule)
######output######
#0.00%
#0.07%
#0.13%
#0.20%
#....
#99.94%
#100.00%
|
通过上面的练习可以知道,urlopen可以轻松获取远端html页面信息,然后通过python正则对所需要的数据进行分析,匹配出想要用的数据,在利用urlretrieve将数据下载到本地。对于访问受限或者对连接数有限制的远程url地址可以采用proxies(代理的方式)连接,如果远程数据量过大,单线程下载太慢的话可以采用多线程下载,这个就是传说中的爬虫。