Reputation:
How do I read back all of the cookies in Python without knowing their names?
Upvotes: 20
Views: 46387
Reputation: 720
An updated answer for 2024 / Python 3.11+, using HTTPSConnection/HTTPResponse
from http.client import HTTPResponse
def get_response_cookies(http_response: HTTPResponse):
cookie_list = http_response.headers.get_all("set-cookie")
if cookie_list is None or len(cookie_list) == 0:
return None
cookies = {}
for cookie_str in cookie_list:
cookie_info = cookie_str.split("; ")
[name, val] = cookie_info[0].split("=")
cookies[name] = val
return cookies
You just have to call this function on your HttpResponse resulting of your connection request:
from http.client import HTTPSConnection
connection = HTTPSConnection(host)
connection.request(method=req_method, url=path_url, body=body, headers=headers)
response = connection.getresponse()
cookies = get_response_cookies(response)
Upvotes: 0
Reputation: 1210
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)
Upvotes: 5
Reputation: 65586
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]
Upvotes: 6
Reputation: 2925
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
Upvotes: 24
Reputation: 882611
Look at the Cookie:
headers in the HTTP response you get, parse their contents with module Cookie
in the standard library.
Upvotes: 4