如何添加一个cookie到cookiejar在python请求库 [英] How to add a cookie to the cookiejar in python requests library

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

问题描述

我想使用python请求1.2.3库来添加一个cookie到现有cookiejar。每次添加新的Cookie时,jar中的数据都将被新建的Cookie覆盖。缺少键,缺少值或与错误键匹配。我不知道是否是一个请求库错误或我没有正确发送cookie。我使用下面的代码,导致cookiejar中的一个坏的cookie。我正确格式化cookie吗?任何想法?

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)


推荐答案

我发现了一种方法来导入CookieJar,Cookie和Cookie。在@Lukasa的帮助下,他给我一个更好的方式。但是,用他的方式,我不能指定port_specified,domain_specified,domain_initial_dot或path_specified属性。 set方法自动使用默认值。我试图抓取一个网站,他们的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)

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

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