开发者

How to display specific cookie?

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜