我正在使用ActivePython 2.5.1和cookielib包来检索网页。
我想从cookiejar而不是整个事物中显示一个给定的cookie:
#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']
我确信这很简单但谷歌搜索却没有返回样本。
谢谢。
答案 0 :(得分:5)
cookiejar没有类似dict的界面,只支持迭代。所以你必须自己实现一个查找方法。
我不确定你想要做什么cookie属性进行查找。例如,使用名称:
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")
如果您不熟悉[...]
语法,则为list comprehension。然后[0]
会选择匹配Cookie列表的第一个元素。