urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件。他以urlopen函数的形式提供了一个非常简单的接口,这是具有利用不同协议获取URLs的能力,他同样提供了一个比较复杂的接口来处理一般情况,例如:基础验证,cookies,代理和其他。它们通过handlers和openers的对象提供。
urllib2支持获取不同格式的URLs(在URL的":"前定义的字串,例如:"ftp"是"ftp:python.ort/"的前缀),它们利用它们相关网络协议(例如FTP,HTTP)进行获取。这篇教程关注最广泛的应用--HTTP。
对于简单的应用,urlopen是非常容易使用的。但当你在打开HTTP的URLs时遇到错误或异常,你将需要一些超文本传输协议(HTTP)的理解。
最权威的HTTP文档当然是RFC 2616(http://rfc.net/rfc2616.html)。这是一个技术文档,所以并不易于阅读。这篇HOWTO教程的目的是展现如何使用urllib2,
并提供足够的HTTP细节来帮助你理解。他并不是urllib2的文档说明,而是起一个辅助作用。
最简单的使用urllib2
代码实例:
1
2
3
|
import urllib2 response = urllib2.urlopen( ‘http://python.org/‘ ) html = response.read() |
urllib2的很多应用就是那么简单(记住,除了"http:",URL同样可以使用"ftp:","file:"等等来替代)。但这篇文章是教授HTTP的更复杂的应用。
HTTP是基于请求和应答机制的--客户端提出请求,服务端提供应答。urllib2用一个Request对象来映射你提出的HTTP请求,在它最简单的使用形式中你将用你要请求的地址创建一个Request对象,通过调用urlopen并传入Request对象,将返回一个相关请求response对象,这个应答对象如同一个文件对象,所以你可以在Response中调用.read()。
1
2
3
4
|
import urllib2 req = urllib2.Request( ‘http://www.python.com‘ ) response = urllib2.urlopen(req) the_page = response.read() |
记得urllib2使用相同的接口处理所有的URL头。例如你可以像下面那样创建一个ftp请求。
req = urllib2.Request(‘ftp://example.com/‘)
在HTTP请求时,允许你做额外的两件事。首先是你能够发送data表单数据,其次你能够传送额外的关于数据或发送本身的信息("metadata")到服务器,此数据作为HTTP的"headers"来发送。
接下来让我们看看这些如何发送的吧。
有时候你希望发送一些数据到URL(通常URL与CGI[通用网关接口]脚本,或其他WEB应用程序挂接)。在HTTP中,这个经常使用熟知的POST请求发送。这个通常在你提交一个HTML表单时由你的浏览器来做。
并不是所有的POSTs都来源于表单,你能够使用POST提交任意的数据到你自己的程序。一般的HTML表单,data需要编码成标准形式。然后做为data参数传到Request对象。编码工作使用urllib的函数而非urllib2。
代码实例:
1
2
3
4
5
6
7
8
9
10
|
import urllib import urllib2 url = ‘http://www.python.com‘ values = { ‘name‘ : ‘Michael Foord‘ , ‘location‘ : ‘pythontab‘ , ‘language‘ : ‘Python‘ } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() |
记住有时需要别的编码(例如从HTML上传文件--看http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13 HTML Specification, Form Submission的详细说明)。
如ugoni没有传送data参数,urllib2使用GET方式的请求。GET和POST请求的不同之处是POST请求通常有"副作用",它们会由于某种途径改变系统状态(例如提交成堆垃圾到你的门口)。
尽管HTTP标准说的很清楚POSTs通常会产生副作用,GET请求不会产生副作用,但没有什么可以阻止GET请求产生副作用,同样POST请求也可能不产生副作用。Data同样可以通过在Get请求的URL本身上面编码来传送。
代码实例:
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> import urllib2 >>> import urllib >>> data = {} >>> data[ ‘name‘ ] = ‘Somebody Here‘ >>> data[ ‘location‘ ] = ‘pythontab‘ >>> data[ ‘language‘ ] = ‘Python‘ >>> url_values = urllib.urlencode(data) >>> print url_values name = blueelwang + Here&language = Python&location = pythontab >>> url = ‘http://www.python.com‘ >>> full_url = url + ‘?‘ + url_values >>> data = urllib2. open (full_url) |
我们将在这里讨论特定的HTTP头,来说明怎样添加headers到你的HTTP请求。
有一些站点不喜欢被程序(非人为访问)访问,或者发送不同版本的内容到不同的浏览器。默认的urllib2把自己作为“Python-urllib/x.y”(x和y是Python主版本和次版本号,例如Python-urllib/2.5),这个身份可能会让站点迷惑,或者干脆不工作。浏览器确认自己身份是通过User-Agent头,当你创建了一个请求对象,你可以给他一个包含头数据的字典。下面的例子发送跟上面一样的内容,但把自身
模拟成Internet Explorer。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import urllib import urllib2 url = ‘http://www.python.com‘ user_agent = ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘ values = { ‘name‘ : ‘Michael Foord‘ , ‘location‘ : ‘pythontab‘ , ‘language‘ : ‘Python‘ } headers = { ‘User-Agent‘ : user_agent } data = urllib.urlencode(values) req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) the_page = response.read() |
response应答对象同样有两个很有用的方法。看下面的节info and geturl,我们将看到当发生错误时会发生什么。
当urlopen不能够处理一个response时,产生urlError(不过通常的Python APIs异常如ValueError,TypeError等也会同时产生)。
HTTPError是urlError的子类,通常在特定HTTP URLs中产生。
通常,URLError在没有网络连接(没有路由到特定服务器),或者服务器不存在的情况下产生。这种情况下,异常同样会带有"reason"属性,它是一个tuple,包含了一个错误号和一个错误信息。
例如
1
2
3
4
5
|
>>> req = urllib2.Request( ‘http://www.python.com‘ ) >>> try : urllib2.urlopen(req) >>> except URLError, e: >>> print e.reason >>> |
(4, ‘getaddrinfo failed‘)
服务器上每一个HTTP 应答对象response包含一个数字"状态码"。有时状态码指出服务器无法完成请求。默认的处理器会为你处理一部分这种应答(例如:假如response是一个"重定向",需要客户端从别的地址获取文档,urllib2将为你处理)。其他不能处理的,urlopen会产生一个HTTPError。典型的错误包含"404"(页面无法找到),"403"(请求禁止),和"401"(带验证请求)。
请看RFC 2616 第十节有所有的HTTP错误码
HTTPError实例产生后会有一个整型‘code‘属性,是服务器发送的相关错误号。
因为默认的处理器处理了重定向(300以外号码),并且100-299范围的号码指示成功,所以你只能看到400-599的错误号码。
BaseHTTPServer.BaseHTTPRequestHandler.response是一个很有用的应答号码字典,显示了RFC 2616使用的所有的应答号。这里为了方便重新展示该字典。
当一个错误号产生后,服务器返回一个HTTP错误号,和一个错误页面。你可以使用HTTPError实例作为页面返回的应答对象response。这表示和错误属性一样,它同样包含了read,geturl,和info方法。
1
2
3
4
5
6
7
|
>>> req = urllib2.Request( ‘http://www.python.org/fish.html‘ ) >>> try : >>> urllib2.urlopen(req) >>> except URLError, e: >>> print e.code >>> print e.read() >>> |
1
2
3
4
|
404 Error 404: File Not Found ...... etc... |
为了方便,代码被复制到了这里:
# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
responses = {
100: (‘Continue‘, ‘Request received, please continue‘),
101: (‘Switching Protocols‘,
‘Switching to new protocol; obey Upgrade header‘),
200: (‘OK‘, ‘Request fulfilled, document follows‘),
201: (‘Created‘, ‘Document created, URL follows‘),
202: (‘Accepted‘,
‘Request accepted, processing continues off-line‘),
203: (‘Non-Authoritative Information‘, ‘Request fulfilled from cache‘),
204: (‘No Content‘, ‘Request fulfilled, nothing follows‘),
205: (‘Reset Content‘, ‘Clear input form for further input.‘),
206: (‘Partial Content‘, ‘Partial content follows.‘),
300: (‘Multiple Choices‘,
‘Object has several resources -- see URI list‘),
301: (‘Moved Permanently‘, ‘Object moved permanently -- see URI list‘),
302: (‘Found‘, ‘Object moved temporarily -- see URI list‘),
303: (‘See Other‘, ‘Object moved -- see Method and URL list‘),
304: (‘Not Modified‘,
‘Document has not changed since given time‘),
305: (‘Use Proxy‘,
‘You must use proxy specified in Location to access this ‘
‘resource.‘),
307: (‘Temporary Redirect‘,
‘Object moved temporarily -- see URI list‘),
400: (‘Bad Request‘,
‘Bad request syntax or unsupported method‘),
401: (‘Unauthorized‘,
‘No permission -- see authorization schemes‘),
402: (‘Payment Required‘,
‘No payment -- see charging schemes‘),
403: (‘Forbidden‘,
‘Request forbidden -- authorization will not help‘),
404: (‘Not Found‘, ‘Nothing matches the given URI‘),
405: (‘Method Not Allowed‘,
‘Specified method is invalid for this server.‘),
406: (‘Not Acceptable‘, ‘URI not available in preferred format.‘),
407: (‘Proxy Authentication Required‘, ‘You must authenticate with ‘
‘this proxy before proceeding.‘),
408: (‘Request Timeout‘, ‘Request timed out; try again later.‘),
409: (‘Conflict‘, ‘Request conflict.‘),
410: (‘Gone‘,
‘URI no longer exists and has been permanently removed.‘),
411: (‘Length Required‘, ‘Client must specify Content-Length.‘),
412: (‘Precondition Failed‘, ‘Precondition in headers is false.‘),
413: (‘Request Entity Too Large‘, ‘Entity is too large.‘),
414: