Python3, Requests: How to merge CookieJars

半世苍凉 提交于 2020-01-04 06:11:57

问题


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 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...

So I tried

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

the third line Fails:

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'

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.....

what am I doing wrong?


回答1:


Try this way

# 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 />]>


来源:https://stackoverflow.com/questions/40692514/python3-requests-how-to-merge-cookiejars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!