How to read cookie in python

此生再无相见时 提交于 2019-12-06 04:25:36

问题


I am new in python cgi script. I want to read cookie in python. I tried following code:

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

But, I see only the cookies are: msg.

Am I doing something wrong?


回答1:


Try this to read cookie in python:

#!/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>



回答2:


If you don't use opener, the cookie jar is not populated.

Access webpage that issue Set-Cookie header.

For example:

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

prints

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/>


来源:https://stackoverflow.com/questions/20898394/how-to-read-cookie-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!