cookielib 模块中定义了一些类来自动处理HTTP请求中的cookieCookieJar()对象 :
CookieJar 存储HTTP请求生成的cookie,并向传出HTTP请求中添加cookie,整个cookie都存在内存中。
FileCookieJar()对象 (LWPCookieJar(xx)对象) 当需要时,可使用FileCookieJar.load(xx)从文件里载入cookie。
urllib2 对 Cookie 的处理也是自动的。如果需要得到某个 Cookie 项的值,可以这么做:
import urllib2 import cookielib cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) response = opener.open('http://www.google.com') for item in cookie: if item.name == 'some_cookie_item_name': print item.value
添加后就可以对每次收到响应中的Set-Cookie 记录到cookie 对象中,下次发送请求的时候就可以把这些Cookies附加到请求中
比如第一次请求:
connect: (www.google.cn, 80) send: 'GET /webhp?source=g_cn HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.cn\r\nConnection: close\r\nUser-Agent: Python-urllib/2.5\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Cache-Control: private, max-age=0 header: Date: Sun, 21 Dec 2008 13:47:39 GMT header: Expires: -1 header: Content-Type: text/html; charset=GB2312 header: Set-Cookie: PREF=ID=5d750b6ffc3d7d04:NW=1:TM=1229867259: LM=1229867259:S=XKoaKmsjYO_-CsHE; expires=Tue, 21-Dec-2010 13:47:39 GMT; path=/; domain=.google.cn header: Server: gws header: Transfer-Encoding: chunked header: Connection: Close
第二次请求中就会附加 Cookie: PREF=ID=5d750b6ffc3d7d04:NW=1:TM=1229867259:LM=1229867259:S=XKoaKmsjYO_-CsHE等Cookie