Python3,要求:如何合并CookieJars [英] Python3, Requests: How to merge CookieJars

查看:109
本文介绍了Python3,要求:如何合并CookieJars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python并使用请求库。
我想使用CookieJar来存储cookie,但是我无法找出如何将响应的Cookies添加到现有的CookieJar:

I am learning Python and using the Requests Lib. I want to use a CookieJar to store cookies, but I cannot find out how to add a response's Cookies to an existing CookieJar:

CookieJar.extract_cookies需要一个请求对象-我不知道要引用哪个请求以及原因。我想将Cookie添加到CookieJar,而不是添加到请求...

CookieJar.extract_cookies requires a request object - I dont understand which request to reference and why. I want to add the Cookies to a CookieJar, not to a request...

所以我尝试了

cj= http.cookiejar.CookieJar()
tmp= requests.utils.dict_from_cookiejar(resp.cookies)
requests.utils.add_dict_to_cookiejar(cj, tmp)

第三行失败:

File "[...]\Python35-32\lib\site-packages\requests\utils.py", line 336, in add_dict_to_cookiejar
    return cookiejar_from_dict(cookie_dict, cj)
  File "[...]\Python35-32\lib\site-packages\requests\cookies.py", line 515, in cookiejar_from_dict
    names_from_jar = [cookie.name for cookie in cookiejar]
  File "[...]\Python35-32\lib\site-packages\requests\cookies.py", line 515, in <listcomp>
    names_from_jar = [cookie.name for cookie in cookiejar]
AttributeError: 'str' object has no attribute 'name'

由于请求的Cookiejar也是字典,所以我终于尝试了
requests.utils.add_dict_to_cookiejar(cj,resp.cookies)

As the Cookiejar of Requests is a dict as well, I finally tried requests.utils.add_dict_to_cookiejar(cj, resp.cookies)

失败并出现相同的错误.....

which Fails with the same error.....

我在做什么错了?

推荐答案

尝试这种方式

# Create cookie one
one = requests.cookies.RequestsCookieJar()

# Create cookie two
two = requests.cookies.RequestsCookieJar()

# set some cookie value
one.set("one_key", "one_value")
two.set("two_key", "two_value")

print(one)
<RequestsCookieJar[<Cookie one_key=one_value for />]>

print(two)
<RequestsCookieJar[<Cookie two_key=two_value for />]>

# Now merge    
one.update(two)
<RequestsCookieJar[<Cookie one_key=one_value for />, <Cookie two_key=two_value for />]>

这篇关于Python3,要求:如何合并CookieJars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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