1、httplib實現了HTTP和HTTPS的客戶端協議,通常不直接使用,在python更高層的封裝模塊中(urllib,urllib2)使用了它的http實現。html
import httplib
conn = httplib.HTTPConnection("google.com")
conn.request('get', '/')
print conn.getresponse().read()
conn.close()
httplib.HTTPConnection ( host [ , port [ , strict [ , timeout ]]] )
HTTPConnection類的構造函數,表示一次與服務器之間的交互,即請求/響應。參數host表示服務器主機,如:http://www.csdn.net/;port爲端口號,默認值爲80; 參數strict的 默認值爲false, 表示在沒法解析服務器返回的狀態行時( status line) (比較典型的狀態行如: HTTP/1.0 200 OK ),是否拋BadStatusLine 異常;可選參數timeout 表示超時時間。
HTTPConnection提供的方法:python
HTTPConnection.request ( method , url [ , body [ , headers ]] )
調用request 方法會向服務器發送一次請求,method 表示請求的方法,經常使用有方法有get 和post ;url 表示請求的資源的url ;body 表示提交到服務器的數據,必須是字符串(若是method 是」post」 ,則能夠把body 理解爲html 表單中的數據);headers 表示請求的http 頭。
HTTPConnection.getresponse ()
獲取Http 響應。返回的對象是HTTPResponse 的實例,關於HTTPResponse 在下面 會講解。
HTTPConnection.connect ()
鏈接到Http 服務器。
HTTPConnection.close ()
關閉與服務器的鏈接。
HTTPConnection.set_debuglevel ( level )
設置高度的級別。參數level 的默認值爲0 ,表示不輸出任何調試信息。
httplib.HTTPResponse
HTTPResponse表示服務器對客戶端請求的響應。每每經過調用HTTPConnection.getresponse()來建立,它有以下方法和屬性:
HTTPResponse.read([amt])
獲取響應的消息體。若是請求的是一個普通的網頁,那麼該方法返回的是頁面的html。可選參數amt表示從響應流中讀取指定字節的數據。
HTTPResponse.getheader(name[, default])
獲取響應頭。Name表示頭域(header field)名,可選參數default在頭域名不存在的狀況下做爲默認值返回。
HTTPResponse.getheaders()
以列表的形式返回全部的頭信息。
HTTPResponse.msg
獲取全部的響應頭信息。
HTTPResponse.version
獲取服務器所使用的http協議版本。11表示http/1.1;10表示http/1.0。
HTTPResponse.status
獲取響應的狀態碼。如:200表示請求成功。
HTTPResponse.reason
返回服務器處理請求的結果說明。通常爲」OK」
下面經過一個例子來熟悉HTTPResponse中的方法:
程序員
import httplib
conn = httplib.HTTPConnection("www.g.com", 80, False)
conn.request('get', '/', headers = {"Host": "www.google.com",
"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
"Accept": "text/plain"})
res = conn.getresponse()
print 'version:', res.version
print 'reason:', res.reason
print 'status:', res.status
print 'msg:', res.msg
print 'headers:', res.getheaders()
#html
#print '\n' + '-' * 50 + '\n'
#print res.read()
conn.close()
Httplib模塊中還定義了許多常量,如:
Httplib. HTTP_PORT 的值爲80,表示默認的端口號爲80;
Httplib.OK 的值爲200,表示請求成功返回;
Httplib. NOT_FOUND 的值爲404,表示請求的資源不存在;
能夠經過httplib.responses 查詢相關變量的含義,如:
Print httplib.responses[httplib.NOT_FOUND] #not found
更多關於httplib的信息,請參考Python手冊httplib 模塊。
urllib 和urllib2實現的功能大同小異,但urllib2要比urllib功能等各方面更高一個層次。目前的HTTP訪問大部分都使用urllib2.服務器
使用例子:cookie
- def use_httplib():
- import httplib
- conn = httplib.HTTPConnection("www.baidu.com")
- i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
- "Accept": "text/plain"}
- conn.request("GET", "/", headers = i_headers)
- r1 = conn.getresponse()
- print "version:", r1.version
- print "reason:", r1.reason
- print "status:", r1.status
- print "msg:", r1.msg
- print "headers:", r1.getheaders()
- data = r1.read()
- print len(data)
- conn.close()
-
- if __name__ == "__main__":
- use_httplib()
2、使用urllib2,太強大網絡
req = urllib2.Request('http://pythoneye.com')
response = urllib2.urlopen(req)
the_page = response.read()
FTP一樣:app
req = urllib2.Request('ftp://pythoneye.com')
urlopen返回的應答對象response有兩個頗有用的方法info()和geturl()
geturl — 這個返回獲取的真實的URL,這個頗有用,由於urlopen(或者opener對象使用的)或許
會有重定向。獲取的URL或許跟請求URL不一樣。
Data數據
有時候你但願發送一些數據到URL
post方式:函數
values ={'body' : 'test short talk','via':'xxxx'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
get方式:
post
data['name'] = 'Somebody Here'
data['location'] = 'Northampton'
data['language'] = 'Python'
url_values = urllib.urlencode(data)
url = 'http://pythoneye.com/example.cgi'
full_url = url + '?' + url_values
data = urllib2.open(full_url)
使用Basic HTTP Authentication:
ui
import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://pythoneye.com/vecrty.py',
user='user',
passwd='pass')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www. pythoneye.com/app.html')
使用代理ProxyHandler:
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.HTTPBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')
URLError–HTTPError:
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
response = urlopen(req)
except HTTPError, e:
print 'Error code: ', e.code
except URLError, e:
print 'Reason: ', e.reason
else:
.............
或者:
from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'):
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'Error code: ', e.code
else:
.............
一般,URLError在沒有網絡鏈接(沒有路由到特定服務器),或者服務器不存在的狀況下產生
異常一樣會帶有」reason」屬性,它是一個tuple,包含了一個錯誤號和一個錯誤信息
req = urllib2.Request('http://pythoneye.com')
try:
urllib2.urlopen(req)
except URLError, e:
print e.reason
print e.code
print e.read()
最後須要注意的就是,當處理URLError和HTTPError的時候,應先處理HTTPError,後處理URLError
Openers和Handlers:
opener使用操做器(handlers)。全部的重活都交給這些handlers來作。每個handler知道
怎麼打開url以一種獨特的url協議(http,ftp等等),或者怎麼處理打開url的某些方面,如,HTTP重定向,或者HTTP
cookie。
默認opener有對普通狀況的操做器 (handlers)- ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.
再看python API:Return an OpenerDirector instance, which chains the handlers in the order given
這就更加證實了一點,那就是opener能夠當作是一個容器,這個容器當中放的是控制器,默認的,容器當中有五個控制
器,程序員也能夠加入本身的控制器,而後這些控制器去幹活。
class HTTPHandler(AbstractHTTPHandler):
def http_open(self, req):
return self.do_open(httplib.HTTPConnection, req)
http_request = AbstractHTTPHandler.do_request_
HTTPHandler是Openers當中的默認控制器之一,看到這個代碼,證明了urllib2是藉助於httplib實現的,同時也證明了Openers和Handlers的關係。