urllib2模塊
urllib模塊和urllib模塊類似,用來打開URL並從中獲取數據。與urllib模塊不同的是,urllib模塊不僅可以使用urlopen() 函數還可以自定義Opener來訪問網頁。同時要注意:urlretrieve()函數是urllib模塊中的,urllib2模塊中不存在該函數。但是 使用urllib2模塊時一般都離不開urllib模塊,因為POST的數據需要使用urllib.urlencode()函數來編碼。
一、urlopen()
最簡單的請求方式就是用urlopen()函數。
urlopen (url [,data ,[timeout]]) 函數打開URL url並返回類文件對象,使用該對象可以讀取返回的內容。其中,參數url 可以是包含URL的字符串,也可以是urllib2.Request類的實例。data是經過編碼的POST數據(一般使用 urllib.urlencode()來編碼)。timeout是可選的超時期(以秒為單位),供所有阻塞操作內部使用。
注意timeout參數,是超時時間,即在中斷連接前嘗試的時間,但只對HTTP、HTTPS、FTP、FTPS有效。設置超時時間,通過 urlopen()函數設置是最簡單的方法,還可以通過socket模塊或urllib2模塊來設置 (socket.setdefaulttimeout(10)或urllib2.socket.setdefaulttimeout(10))。詳細代碼 參考《urllib2的使用細節》.
urlopen()返回的類文件對象u支持一下方法:
對於簡單的請求,urlopen()的參數url就是一個代表URL的字符串。但如果需要執行更復雜的操作,如修改HTTP報頭,可以創建Request實例並將其作為url參數。
Request (url [data,headers [,origin_req_host ,[unverifiable]]]])
Request實例r具有的方法中重要的有以下幾個:
下面代碼示例使用Request來更改urlopen()使用的User-Agent報頭的方法:
headers={"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"} rq=urllib2.Request("http://www.example.com",headers=headers) u=urlopen(rg)
二、自定義Opener
基本的urlopen()函數不支持驗證、cookie或其他HTTP高級功能。要支持這些功能,必須使用build_opener()函數來創建自己的自定義Opener對象。
install_opener(opener) 安裝opener作為urlopen()使用的全局URL opener,即意味着以后調用urlopen()時都會使用安裝的opener對象。opener通常是build_opener()創建的 opener對象。
復雜情況詳細解決辦法:
1、cookie處理
如果要管理HTTP cookie,需要創建添加了HTTPCookieProcessor處理程序的opener對象。默認情況下。HTTPCookieProcessor 使用CookieJar對象,將不同類型的CookieJar對象作為HTTPCookieProcessor的參數提供,可支持不同的cookie處 理。如下面代碼:
mcj=cookielib.MozillaCookieJar("cookies.txt") cookiehand=HTTPCookieProcessor(mcj) opener=urllib2.build_opener(cookiehand) u=opener.open(http://www.baidu.com)
2、密碼驗證
3、代理
urllib2會自動檢測代理設置,默認使用環境變量http_proxy 來設置 HTTP Proxy通常情況下,這是很有幫助的,因為也可能造成麻煩(因為通過代理獲取本地URL資源時會被阻止,因此如果你正在通過代理訪問Internet, 那么使用腳本測試本地服務器時必須阻止urllib2模塊使用代理)。因此,如果想在程序中明確Proxy的使用而不受環境變量的影響,可以通過創建 ProxyHandler實例,並將實例作為build_opener()的參數來實現。如下面代碼:
import urllib2 enable_proxy = True proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'}) null_proxy_handler = urllib2.ProxyHandler({}) if enable_proxy: opener = urllib2.build_opener(proxy_handler) else: opener = urllib2.build_opener(null_proxy_handler) urllib2.install_opener(opener)
cookielib模塊
cookielib模塊的主要作用是提供可存儲cookie的對象,以便於與urllib2模塊配合使用來訪問Internet資源。例如可以利用本模塊 的CookieJar類的對象來捕獲cookie並在后續連接請求時重新發送。coiokielib模塊用到的對象主要有下面幾個:CookieJar、 FileCookieJar、MozillaCookieJar、LWPCookieJar。其中他們的關系如下:
CookieJar
/
FileCookieJar
/ \
MozillaCookieJar LWPCookieJar
1、CookieJar ()
管理HTTP cookie值、存儲HTTP請求生成的cookie、向傳出的HTTP請求添加cookie的對象。整個cookie都存儲在內存中,對CookieJar實例進行垃圾回收后cookie也將丟失。
The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses.CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.
2、FileCookieJar (filename,delayload=None,policy=None)
創建FileCookieJar實例,檢索cookie信息並將cookie存儲到文件中。filename是存儲cookie的文件名。delayload為True時支持延遲訪問訪問文件,即只有在需要時才讀取文件或在文件中存儲數據。
A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called.
3、MozillaCookieJar (filename,delayload=None,policy=None)
創建與Mozilla瀏覽器cookies.txt兼容的FileCookieJar實例。
A FileCookieJar that can load from and save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers).Also note that cookies saved while Mozilla is running will get clobbered by Mozilla.
4、LWPCookieJar (filename,delayload=None,policy=None)
創建與libwww-perl的Set-Cookie3文件格式兼容的FileCookieJar實例。
A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3file format. This is convenient if you want to store cookies in a human-readable file.
除了上面幾個函數之外,下面幾個函數也很重要:
- FileCookieJar. save ( filename=None , ignore_discard=False , ignore_expires=False )
-
Save cookies to a file.This base class raises NotImplementedError. Subclasses may leave this method unimplemented.filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised. ignore_discard: save even cookies set to be discarded. ignore_expires: save even cookies that have expiredThe file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.
- FileCookieJar. load ( filename=None , ignore_discard=False , ignore_expires=False )
-
Load cookies from a file.Old cookies are kept unless overwritten by newly loaded ones.Arguments are as for save().The named file must be in the format understood by the class, or LoadError will be raised. Also, IOError may be raised, for example if the file does not exist.
- FileCookieJar. revert ( filename=None , ignore_discard=False , ignore_expires=False )
-
Clear all cookies and reload cookies from a saved file. revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.
-
cookielib模塊一般與urllib2模塊配合使用,主要用在urllib2.build_oper()函數中作為urllib2.HTTPCookieProcessor()的參數。使用方法如下面登錄人人網的代碼:
#! /usr/bin/env python #coding=utf-8 import urllib2 import urllib import cookielib data={"email":"用戶名","password":"密碼"} #登陸用戶名和密碼 post_data=urllib.urlencode(data) cj=cookielib.CookieJar() opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"} req=urllib2.Request("http://www.renren.com/PLogin.do",post_data,headers) content=opener.open(req) print content2.read().decode("utf-8").encode("gbk")