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

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

问题描述

我正在尝试使用 python requests 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)

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

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