如何在python中读取cookie

时间:2014-01-03 07:05:23

标签: python cookies cgi

我是python cgi脚本的新手。我想在python中读取cookie。我尝试了以下代码:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()

#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie

但是,我只看到the cookies are:消息。

我做错了吗?

2 个答案:

答案 0 :(得分:4)

尝试这样在python中读取cookie:

#!/usr/bin/python

import os

# Hello world python program
print "Content-Type: text/html;charset=utf-8";
print

handler = {}
if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')

    for cookie in cookies:
        cookie = cookie.split('=')
        handler[cookie[0]] = cookie[1]

for k in handler:
    print k + " = " + handler[k] + "<br>

答案 1 :(得分:0)

如果您不使用opener,则不会填充cookie jar。

访问发出Set-Cookie标题的网页。

例如:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()

#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

response = opener.open('http://google.com/') # <---
response.read()

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie

打印

the cookies are:
<Cookie NID=67=aBkBw0UEgv... for .google.co.kr/>
<Cookie PREF=ID=b99fae87d... for .google.co.kr
<Cookie NID=67=c8QgK_rfyf... for .google.com/>
<Cookie PREF=ID=dbb574e7d... for .google.com/>