20
votes

How do I read back all of the cookies in Python without knowing their names?

4
When you say "read them back", do you mean a) read them from an HTTP response, or b) read them out of the CookieJar? Or is there a (c) interpretation? - Jarret Hardie
There is a (c) as well :) c_1) Someone might ask about the cookies of HIS python session... E.g. if the python script is a .cgi ( for that see e.g. os.environ['HTTP_COOKIE'] answer by Matt Lacey, depending on the web server used to serve the cgi) c_2) Same question if its a notebook running in jupyter (web server is tornado) - ntg

4 Answers

24
votes

Not sure if this is what you are looking for, but here is a simple example where you put cookies in a cookiejar and read them back:

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())

#create a request object to be used to get the page.
req = Request("http://www.about.com")
f = opener.open(req)

#see the first few lines of the page
html = f.read()
print html[:50]

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

Put os.environ['HTTP_COOKIE'] into an array:

#!/usr/bin/env python

import os

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

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

This may be exactly what you are looking for.

Python 3.4

import requests

r = requests.get('http://www.about.com/')
c = r.cookies
i = c.items()

for name, value in i:
    print(name, value)
4
votes

Look at the Cookie: headers in the HTTP response you get, parse their contents with module Cookie in the standard library.