urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件。他以urlopen函数的形式提供了一个很是简单的接口,这是具备利用不一样协议获取URLs的能力,他一样提供了一个比较复杂的接口来处理通常状况,例如:基础验证,cookies,代理和其余。它们经过handlers和openers的对象提供。html
urllib2支持获取不一样格式的URLs(在URL的":"前定义的字串,例如:"ftp"是"ftp:python.ort/"的前缀),它们利用它们相关网络协议(例如FTP,HTTP)进行获取。这篇教程关注最普遍的应用--HTTP。python
对于简单的应用,urlopen是很是容易使用的。但当你在打开HTTP的URLs时遇到错误或异常,你将须要一些超文本传输协议(HTTP)的理解。浏览器
最权威的HTTP文档固然是RFC 2616(http://rfc.net/rfc2616.html)。这是一个技术文档,因此并不易于阅读。这篇HOWTO教程的目的是展示如何使用urllib2,bash
并提供足够的HTTP细节来帮助你理解。他并非urllib2的文档说明,而是起一个辅助做用。服务器
最简单的使用urllib2cookie
代码实例:网络
1
2
3
|
import
urllib2
response
=
urllib2.urlopen(
'http://python.org/'
)
html
=
response.read()
|
urllib2的不少应用就是那么简单(记住,除了"http:",URL一样可使用"ftp:","file:"等等来替代)。但这篇文章是教授HTTP的更复杂的应用。app
HTTP是基于请求和应答机制的--客户端提出请求,服务端提供应答。urllib2用一个Request对象来映射你提出的HTTP请求,在它最简单的使用形式中你将用你要请求的地址建立一个Request对象,经过调用urlopen并传入Request对象,将返回一个相关请求response对象,这个应答对象如同一个文件对象,因此你能够在Response中调用.read()。socket
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: