如何创建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'
看着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。
这里的关键点是方法 cj.set_cookie
期待一个类的对象 cookielib.Cookie
作为其参数(所以 是的,还有另一个Cookie类) 不 一个阶级的对象 Cookie.SimpleCookie
(或模块中的任何其他类 Cookie
)。尽管名称的相似性令人困惑,但这些类(如所观察到的)根本不兼容。
注意构造函数的参数列表 cookielib.Cookie
可能在过去的某个时候发生了变化(并且可能会在未来再次发生变化,因为这个类似乎不会在 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
参数和参数 rfc2109
虽然在上面@ Michael的答案中的代码中使用但没有记录,所以示例应该变成类似的东西
c = Cookie(None, 'asdf', None, '80', True, 'www.foo.bar',
True, False, '/', True, False, '1370002304', False, 'TestCookie', None, None, False)
(也替换了一些布尔常量 None
适用时)。