Get cookie from CookieJar by name
Asked Answered
T

4

35

I know that I can iterate through the cookies in a cookiejar, and this would allow me to find a cookie with a particular name - but does the CookieJar object itself have any methods I can call to get a certain cookie by name?

It just saves me having to write a helper method that already exists.

Tunable answered 17/11, 2011 at 23:37 Comment(1)
Not that I can see, no. You could make a function or subclass the CookieJar object, but I'm not sure why no method exists.Alienation
P
36

Yes, the __iter__ method will go through each cookie in CookieJar.

for cookie in cj:
   print cookie.name, cookie.value, cookie.domain #etc etc

A cookie is not just a name and value pair. In its long list (17) of properties, there is domain and path. A domain value of .ibm.com would be applicable to the website mail.ibm.com for example. A domain value of ibm.com and path value of /abc would not apply to the web page ibm.com/index.htm. So by supplying the name alone is insufficient to find the value of an applicable cookie in CookieJar.

Though the __iter__ method will return a list of cookie objects easily, example list(cj), the internal structure of CookieJar is not a simple list. Internals about the CookieJar class is here.

Parrisch answered 17/12, 2014 at 10:52 Comment(0)
T
32

You can also use dict_from_cookiejar, which returns a key/value dictionary from a CookieJar. Something like:

my_cookies = requests.utils.dict_from_cookiejar(s.cookies)

and then access your cookie value by key.

Thallic answered 3/6, 2015 at 13:46 Comment(0)
R
8

It's undocumented internals, but you can access cookies directly like this: cookiejar._cookies[domain][path][name]

Rebeca answered 3/4, 2016 at 15:3 Comment(0)
T
1

cookielib.CookieJar?

you can convert jar to a list and process that, e.g. {i.name: i for i in list(j)}

and btw, j._cookies is actually a dict-dict already, though not completely trivially indexed.

cookie jar file?

I thought those were plain text files...

Thanksgiving answered 8/10, 2012 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.