我正在学习Python并使用Requests Lib。 我想使用CookieJar存储cookie,但我无法找到如何将响应的Cookie添加到现有的CookieJar中:
CookieJar.extract_cookies需要一个请求对象 - 我不明白要引用哪个请求以及原因。我想将Cookie添加到CookieJar,而不是请求...
所以我试过
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)
失败并出现同样的错误.....
我做错了什么?
答案 0 :(得分:1)
试试这种方式
# 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 />]>