Python urllib 库提供了一个从指定的 URL 地址获取网页数据,然后对其进行分析处理,获取想要的数据。
下面是在 Python Shell 里的 urllib 的使用情况:
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. |
05 |
>>> print 'http header:\n' ,google.info() |
07 |
Date: Wed, 30 Oct 2013 03 : 11 : 44 GMT |
09 |
Cache - Control: private, max - age = 0 |
10 |
Content - Type : text / html; charset = Big5 |
11 |
Set - Cookie: PREF = ID = 7ee0cbd58be6fb74 :FF = 0 :NW = 1 :TM = 1383102704 :LM = 1383102704 :S = w6DoLuUBc7KUOE69; expires = Fri, 30 - Oct - 2015 03 : 11 : 44 GMT; path = / ; domain = .google.com.hk |
12 |
Set - Cookie: NID = 67 = cNyh4vZeoDJFnSe12viwoMNh47Hjq98F72I6TTNZGBuJx78aRgQbAA - RtGNFFpARCaN3zJ6OYIpJASB3Q7cmfyRguFh6epcBOSL930KEfIxUa - 85e946hE97WfP0lgk7 ; expires = Thu, 01 - May - 2014 03 : 11 : 44 GMT; path = / ; domain = .google.com.hk; HttpOnly |
15 |
X - XSS - Protection: 1 ; mode = block |
16 |
X - Frame - Options: SAMEORIGIN |
17 |
Alternate - Protocol: 80 :quic |
19 |
>>> print 'http status:' ,google.getcode() |
21 |
>>> print 'url:' ,google.geturl() |
22 |
url: http: / / www.google.com.hk / |
上面主要用到了 urllib 库里的 urlopen() 函数。我们可以了解一下这个函数。
继续使用 Python Shell:
1 |
>>> help (urllib.urlopen) |
2 |
Help on function urlopen in module urllib: |
4 |
urlopen(url, data = None , proxies = None ) |
5 |
Create a file - like object for the specified URL to read from . |
即创建一个类文件对象为指定的 url 来读取。
详细点就是,创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远程数据。参数url表示远程数据的路径,一般是网址;参数data表示以post方式提交到url的数据(玩过web的人应该知道提交数据的两种方式:post与get。如果你不清楚,也不必太在意,一般情况下很少用到这个参数);参数proxies用于设置代理(这里不详细讲怎么使用代理,感兴趣的看客可以去翻阅Python手册urllib模块)。urlopen返回 一个类文件对象,他提供了如下方法:
- 参数 url 表示远程数据的路径,一般是 http 或者 ftp 路径。
- 参数 data 表示以 get 或者 post 方式提交到 url 的数据。
- 参数 proxies 表示用于代理的设置。
urlopen 返回一个类文件对象,它提供了如下方法:
- read() , readline() , readlines(),fileno()和close(): 这些方法的使用与文件对象完全一样。
- info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息。
- getcode():返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到。
- geturl():返回请求的url地址。
再看一个例子,这个例子把Google首页的html抓取下来并显示在控制台上:
再运行一下这个例子,以加深对urllib的印象:
2 |
print 'http header:/n' , google.info() |
3 |
print 'http status:' , google.getcode() |
4 |
print 'url:' , google.geturl() |