python - 添加cookie到cookiejar [英] python - add cookie to cookiejar

查看:357
本文介绍了python - 添加cookie到cookiejar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I create a cookie and add it to a CookieJar instance in python? I have all the info for the cookie (name, value, domain, path, etc) and I don't want to extract a new cookie with a http request.

我试过这个,但它看起来像SimpleCookie类不兼容CookieJar(是否有另一个Cookie类?)

I tried this but it looks like SimpleCookie class is not compatible with CookieJar (is there another Cookie class?)

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,你会得到:

Looking at cookielib, you get:

from cookielib import Cookie, CookieJar
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。

There are no real sanity checks for the instantiation parameters. The ports have to be strings, not int.

这篇关于python - 添加cookie到cookiejar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆