python cookiejar_如何添加一个cookie到cookiejar在python请求库

I am trying to add a cookie to an existing cookiejar using the python requests 1.2.3 library. Every time I add the new cookie, the data in the jar is munged for the new cookie. Keys missing, Values missing or matched to incorrect Keys. I'm not sure if it's a Request library bug or I'm not sending the cookie correctly. I'm using the following code that is resulting in a bad cookie in cookiejar. Am I formatting the cookie correctly? Any ideas?

my_cookie = {

'domain':'www.mydomain.com',

'expires':None,

'name':'COOKIE_NAME',

'path':'/',

'value':'the cookie works',

'version':0

}

s = requests.Session()

requests.utils.add_dict_to_cookiejar(s.cookies, my_cookie)

解决方案

I found out a way to do it by importing CookieJar, Cookie, and cookies. With help from @Lukasa, he showed me a better way. However, with his way I was not able to specify the "port_specified", "domain_specified", "domain_initial_dot" or "path_specified" attributes. The "set" method does it automatically with default values. I'm trying to scrape a website and their cookie has different values in those attributes. As I am new to all of this I'm not sure if that really matters yet.

my_cookie = {

"version":0,

"name":'COOKIE_NAME',

"value":'true',

"port":None,

# "port_specified":False,

"domain":'www.mydomain.com',

# "domain_specified":False,

# "domain_initial_dot":False,

"path":'/',

# "path_specified":True,

"secure":False,

"expires":None,

"discard":True,

"comment":None,

"comment_url":None,

"rest":{},

"rfc2109":False

}

s = requests.Session()

s.cookies.set(**my_cookie)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值