如何创建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。
关于python-将cookie添加到cookiejar,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4685337/