版本是python2.7,
3.x的版本urllib與urllib2已經合併爲一個urllib庫,學着比較清晰些,2.7的版本呢urllib與urllib2各有各的作用
urllib2可以接受一個Request對象,並以此可以來設置一個URL的headers
1.
urlopen方法也可通過建立了一個Request對象來明確指明想要獲取的url。調用urlopen函數對請求的url返回一個response對象。這個response類似於一個file對象,所以用.read()函數可以操作這個response對象
import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read()
2.
URL——是一個字符串,其中包含一個有效的URL。
data——是一個字符串,指定額外的數據發送到服務器,如果沒有data需要發送可以爲“None”。目前使用data的HTTP請求是唯一的。當請求含有data參數時,HTTP的請求爲POST,而不是GET。數據應該是緩存在一個標準的application/x-www-form-urlencoded格式中。urllib.urlencode()函數用映射或2元組,返回一個這種格式的字符串。通俗的說就是如果想向一個URL發送數據(通常這些數據是代表一些CGI腳本或者其他的web應用)。對於HTTP來說這動作叫Post。例如在網上填的form(表單)時,瀏覽器會POST表單的內容,這些數據需要被以標準的格式編碼(encode),然後作爲一個數據參數傳送給Request對象。Encoding是在urlib模塊中完成的,而不是在urlib2中完成的.
headers——是字典類型,頭字典可以作爲參數在request時直接傳入,也可以把每個鍵和值作爲參數調用add_header()方法來添加。作爲辨別瀏覽器身份的User-Agent header是經常被用來惡搞和僞裝的,因爲一些HTTP服務只允許某些請求來自常見的瀏覽器而不是腳本,或是針對不同的瀏覽器返回不同的版本。例如,Mozilla Firefox瀏覽器被識別爲“Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11”。默認情況下,urlib2把自己識別爲Python-urllib/x.y(這裏的xy是python發行版的主要或次要的版本號,如在Python 2.6中,urllib2的默認用戶代理字符串是“Python-urllib/2.6。
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent =
'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' :
'Michael Foord',
'location' :
'Northampton',
'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()
import
urllib2
request
=
urllib2.Request(uri)
request.add_header(
'User-Agent'
,
'fake-client'
)
response
=
urllib2.urlopen(request)
import urllib2
req = urllib2.Request('http://python.org')
response = urllib2.urlopen(req)
the_page = response.read() print the_page
3.
Headers
在這裏討論一個特定的HTTP頭,說明如何添加頭到你的HTTP請求。
一些網站(google)不喜歡由程序來訪問或不同的瀏覽器發送不同的版本,默認情況下,urllib2標識自己爲python urllib / x.y(x.y是Python版本號eg : 2.7),這個可能會混淆網站,或只是簡單的不工作。
瀏覽器標識自己的方式是通過用戶代理(User-Agent)頭。當創建一個Request對象時,你可以通過一個Headers的字典。下面的例子使相同的請求,但將其標識爲一個版本的Internet Explorer。
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {}
values['name'] = 'Michael Foord'
values['location'] = 'Northampton'
values['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()
print the_page
response還有兩個常用的方法(info、geturl)。
4.Handling Exceptions
當urlopen無法處理響應時將引起URLError(儘管像往常一樣使用Python APIs,內建的異常如ValueError、TypeError等也可以引起),在特定的HTTP URLs情況下,HTTPError 是URLError的子類。
URLError
通常,網絡沒有連接或沒有路由到指定的服務器或指定的服務器不存在將引起URLError.在這種情形下,異常引發將有個reason屬性,這是一個包含錯誤代碼和一個文本錯誤信息的元組。
import urllib2
req = urllib2.Request('http://www.pretend_server.org')
try:
urllib2.urlopen(req)
except urllib2.URLError,e:
print e.reason
[Errno 11004] getaddrinfo failed
HTTPError
每個HTTP響應從服務器包含一個數字狀態碼”,有時,這個狀態碼錶明服務器無法滿足請求。默認處理程序將處理一些響應(例如:如果響應是一個“重定向”,則要求客戶端從不同的網址提取文檔,urllib2將自行處理);對於那些它不能處理的,urlopen將引起HTTPError。典型的錯誤包括404(沒有找到網頁)、403(禁止請求)、401(需要驗證)。
HTTPError 實例提出的將一個整型的’code ‘屬性,對應服務器發出的錯誤Error Codes。因爲默認處理程序處理重定向(代碼在300範圍內),代碼在100-299表明成功,你通常會看到在400-599範圍錯誤代碼。
basehttpserver.basehttprequesthandler.responses是一個有用的字典響應碼,顯示所有的的響應碼由RFC2616的應用。
# 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: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}
服務器響應引起的錯誤通過返回一個HTTP錯誤代碼和錯誤頁面,可以使用HTTPError實例爲頁面上的響應中返回。這個也有code屬性,也有read、geturl、info方法。
import urllib2
req = urllib2.Request('http://www.python.org/fish.html')
try:
urllib2.urlopen(req)
except urllib2.URLError,e:
print e.code
print e.read()
print e.geturl()
print e.info()