python - 将cookie添加到cookiejar

时间:2011-01-13 21:14:04

标签: python cookies

如何创建cookie并将其添加到python中的CookieJar实例? 我有cookie的所有信息(名称,值,域,路径等),我不想提取带有http请求的新cookie。

我试过这个,但看起来SimpleCookie类与CookieJar不兼容(还有另一个Cookie类吗?)

import Cookie
c = Cookie.SimpleCookie()
c["name"]="value"
c['name']['expires'] = 0
c['name']['path'] = "/"
c['name']['domain'] = "mydomain.com"
cj = cookielib.CookieJar()
cj.set_cookie(cookie)

Traceback (most recent call last):
    cj.set_cookie(cookie)
  File "/usr/lib/python2.6/cookielib.py", line 1627, in set_cookie
    if cookie.domain not in c: c[cookie.domain] = {}
AttributeError: 'SimpleCookie' object has no attribute 'domain'

2 个答案:

答案 0 :(得分:11)

看着cookielib,你得到:

try:
    from cookielib import Cookie, CookieJar         # Python 2
except ImportError:
    from http.cookiejar import Cookie, CookieJar    # Python 3
cj = CookieJar()
# Cookie(version, name, value, port, port_specified, domain, 
# domain_specified, domain_initial_dot, path, path_specified, 
# secure, discard, comment, comment_url, rest)
c = Cookie(None, 'asdf', None, '80', '80', 'www.foo.bar', 
       None, None, '/', None, False, False, 'TestCookie', None, None, None)
cj.set_cookie(c)
print cj

给出:

<cookielib.CookieJar[<Cookie asdf for www.foo.bar:80/>]>

实例化参数没有真正的健全性检查。端口必须是字符串,而不是int。

答案 1 :(得分:2)

这里的关键点是方法cj.set_cookie期望类cookielib.Cookie的对象作为其参数(所以是,还有另一个Cookie类), not Cookie.SimpleCookie的对象(或模块Cookie中找到的任何其他类)。尽管名称的相似性令人困惑,但这些类(如所观察到的)根本不兼容。

请注意,cookielib.Cookie的构造函数的参数列表可能在过去的某个时间点已更改(并且将来可能会再次更改,因为此类似乎不会在{{{}之外使用1}}),至少cookielib目前给了我

help(cookielib.Cookie)

请注意额外的# Cookie(version, name, value, port, port_specified, domain, # domain_specified, domain_initial_dot, path, path_specified, # secure, expires, discard, comment, comment_url, rest, rfc2109=False) 参数和参数expires,但未在上面@ Michael的答案中的代码中记录,因此该示例应该变为类似

rfc2109

(也适用于替换c = Cookie(None, 'asdf', None, '80', True, 'www.foo.bar', True, False, '/', True, False, '1370002304', False, 'TestCookie', None, None, False) 的一些布尔常量)。

相关问题