Python網路編程中urllib2模組的用法總結,pythonurllib2

來源:互聯網
上載者:User

Python網路編程中urllib2模組的用法總結,pythonurllib2

一、最基礎的應用

import urllib2url = r'http://www.baidu.com'html = urllib2.urlopen(url).read()print html

用戶端與伺服器端通過request與response來溝通,用戶端先向服務端發送request,然後接收服務端返回的response

urllib2提供了request的類,可以讓使用者在發送請求前先構造一個request的對象,然後通過urllib2.urlopen方法來發送請求

import urllib2url = r'http://www.baidu.com'req = urllib2.Request(url)html = urllib2.urlopen(req).read()print html

上例中先使用

req = urllib2.Request(url)

執行個體化一個resquest對象,接下來使用

urllib2.urlopen(req)

來開啟這個網頁。

我們注意到在執行個體化Request對象的時候,隊了url是必須的,還有幾個預設的參數

基中data與header也是使用的比較多的,一些需要登入的才能瀏覽的網站經常需要這兩個參數

import urllib import urllib2  url = 'http://www.baidu.com/' values = {'name' : 'Michael Foord', 'location' : 'Northampton','language' : 'Python' } data = urllib.urlencode(values) req = urllib2.Request(url,data) response = urllib2.urlopen(req) the_page = response.read()print the_page

這個例子是向百度發送幾個資料,這個例子是會返回一個錯誤頁面,很正常,因為我們在訪問百度的時候並不需要post什麼資訊,post了倒是會出錯

百度是找不到相應的網頁就會報錯。

當然這個是POST資料,也可以用在GET方法,稍將上面的代碼進行改造

百度是通過http://www.baidu.com/s?wd=XXX 來進行查詢的,這樣我們需要將{‘wd':'xxx'}這個字典進行urlencode

#coding:utf-8import urllib import urllib2  url = 'http://www.baidu.com/s' values = {'wd':'楊彥星'} data = urllib.urlencode(values)print data url2 = url+'?'+dataresponse = urllib2.urlopen(url2) the_page = response.read()print the_page

以下以類比登入人人網然後再顯示首頁內容為例來詳細說明一下cookie的使用,以下是文檔中給的例子,我們就通過改造這個例子來實現我們想要的功能

import cookielib, urllib2cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))r = opener.open("http://example.com/") #coding:utf-8import urllib2,urllibimport cookieliburl = r'http://www.renren.com/ajaxLogin'#建立一個cj的cookie的容器cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))#將要POST出去的資料進行編碼data = urllib.urlencode({"email":email,"password":pass})r = opener.open(url,data)print cj

當你看到有cj的時候,說明你已經訪問了登入頁面,是否正常登入你現在還看不出來,可以通過訪問http://www.renren.com/home 來查看

上面的代碼有兩點要說明,我也是看了很長時間才明白

r = opener.open(url,data) 

這句,為什麼要使用opener這個對象來open,而不是用utllib2,urlopen?不光是例子裡這麼寫,我們才這麼寫,通過改造我們也可以使用urllib2.urlopen,其實是因為opener是urllib2.bulid_opener創造出來的, 但是你可以這樣理解,他build出來後,自已卻並沒有安裝使用它,也沒有它的屬性與方法,如果想使urllib2也具有opener的屬性與方法,可以先使用urllib2.install_opener(opener)來"安裝"這個opener,安裝完以後就可以使用urllib2來操作了

#coding:utf-8import urllib2,urllibimport cookieliburl = r'http://www.renren.com/ajaxLogin'#建立一個cj的cookie的容器cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))urllib2.install_opener(opener)#將要POST出去的資料進行編碼data = urllib.urlencode({"email":email,"password":pass})#r = opener.open(url,data)如果沒有上面的urllib2.install_opener方法,就必須這樣寫了r = urllib2.urlopen(url,data)html = urllib2.urlopen('http://www.renren.com/home').read()print html

同樣urllib2還有proxy相關的handle,基本的思路和這個差不多。

二、異常處理

當urlopen()不能處理響應時會引起URLError異常。HTTPError異常是URLError的一個子類,只有在訪問HTTP類型的URL時才會引起。

1、URLError異常

通常引起URLError的原因是:無網路連接(沒有到目標伺服器的路由)、訪問的目標伺服器不存在。在這種情況下,異常對象會有reason屬性(是一個(錯誤碼、錯誤原因)的元組)。

#! /usr/bin/env python#coding=utf-8import urllib2url="http://www.baidu.com/"try: response=urllib2.urlopen(url)except urllib2.URLError,e: print e.reason

2、HTTPError
每一個從伺服器返回的HTTP響應都有一個狀態代碼。其中,有的狀態代碼表示伺服器不能完成相應的請求,預設的處理常式可以為我們處理一些這樣的狀態代碼(如返回的響應是重新導向,urllib2會自動為我們從重新導向後的頁面中擷取資訊)。有些狀態代碼,urllib2模組不能幫我們處理,那麼urlopen函數就會引起HTTPError異常,其中典型的有404/401。
HTTPError異常的執行個體有整數類型的code屬性,表示伺服器返回的錯誤狀態代碼。
urllib2模組預設的處理常式可以處理重新導向(狀態代碼是300範圍),而且狀態代碼在100-299範圍內表示成功。因此,能夠引起HTTPError異常的狀態代碼範圍是:400-599.
當引起錯誤時,伺服器會返回HTTP錯誤碼和錯誤頁面。你可以將HTPError執行個體作為返回頁面,這意味著,HTTPError執行個體不僅有code屬性,還有read、geturl、info等方法。

#! /usr/bin/env python#coding=utf-8import urllib2url="http://cs.scu.edu.cn/~duanlei"try: response=urllib2.urlopen(url)except urllib2.HTTPError,e: print e.code print e.read()

3、總結
如果想在代碼中處理URLError和HTTPError有兩種方法,代碼如下:

#! /usr/bin/env python#coding=utf-8import urllib2url="xxxxxx" #需要訪問的URLtry: response=urllib2.urlopen(url)except urllib2.HTTPError,e: #HTTPError必須排在URLError的前面 print "The server couldn't fulfill the request" print "Error code:",e.code print "Return content:",e.read()except urllib2.URLError,e: print "Failed to reach the server" print "The reason:",e.reasonelse: #something you should do pass #其他異常的處理#! /usr/bin/env python#coding=utf-8import urllib2url="http://xxx" #需要訪問的URLtry: response=urllib2.urlopen(url)except urllib2.URLError,e: if hasattr(e,"reason"): print "Failed to reach the server" print "The reason:",e.reason elif hasattr(e,"code"): print "The server couldn't fulfill the request" print "Error code:",e.code print "Return content:",e.read()else: pass #其他異常的處理

相比較而言,第二種異常處理方法更優。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.