views:

20

answers:

1

Hello,

I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages.

I'd like to display a given cookie from the cookiejar instead of the whole thing:

#OK to display all the cookies
for index, cookie in enumerate(cj):
    print index, '  :  ', cookie        

#How to display just PHPSESSID?
#AttributeError: CookieJar instance has no attribute '__getitem__'
print "PHPSESSID: %s" % cj['PHPSESSID']

I'm sure it's very simple but googling for this didn't return samples.

Thank you.

A: 

The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself.

I am not sure what cookie attribute you want do do the lookup on. Example, using name:

def get_cookie_by_name(cj, name):
    return [cookie for cookie in cj if cookie.name == name][0]

cookie = get_cookie_by_name(cj, "PHPSESSID")

If you're not familiar with the [...] syntax, it is a list comprehension. The [0] then picks the first element of the list of matching cookies.

codeape
Thanks for the tip.
OverTheRainbow