为什么合并requests.cookies.RequestsCookieJar()对象根本不起作用?

时间:2018-02-19 23:45:42

标签: python python-3.x cookies python-requests

我有这个词:

cloudflare_cookies = {'__cfduid': 'd46ed690cd9088175f95adcbc6775ee351519082779', 'cf_clearance': '6f72b46f12e0f5491e84abc94772c48149b768ef-1519082786-86400'}

然后,我想从该dict变量中的两个cookie创建一个 requests.cookies.RequestsCookieJar()对象,如:

    cookie1 = {
                  name: '__cfduid'
                  value: 'd46ed690cd9088175f95adcbc6775ee351519082779'
               }

    cookie2 = {
                  name: 'cf_clearance'
                  value: '6f72b46f12e0f5491e84abc94772c48149b768ef-1519082786-86400'
              }

   cookie_final = cookie1 + cookie2

我的代码是以下内容:

    cookie1 = requests.cookies.RequestsCookieJar()
    cookie2 = requests.cookies.RequestsCookieJar()
    cookie1.set("name", "__cfduid")
    cookie1.set("value", cloudflare_cookies['__cfduid'])
    cookie2.set("name", "cf_clearance")
    cookie2.set("value", cloudflare_cookies['cf_clearance'])
    cookie_final = requests.cookies.merge_cookies(cookie1,cookie2)
    print (cloudflare_cookies)
    print (cookie_final)

但我打印的是:

{'__cfduid': 'd46ed690cd9088175f95adcbc6775ee351519082779', 'cf_clearance': '6f72b46f12e0f5491e84abc94772c48149b768ef-1519082786-86400'}
<RequestsCookieJar[<Cookie name=cf_clearance for />, <Cookie value=6f72b46f12e0f5491e84abc94772c48149b768ef-1519082786-86400 for />]>

最后只有 cookie2 位于 cookie_final 内。 我已经尝试过cookie1.update(cookie2),最后,cookie2最终取代了cookie1。

可能出现什么问题???

1 个答案:

答案 0 :(得分:1)

此代码:

import requests

cloudflare_cookies = {'__cfduid': 'd46ed690cd9088175f95adcbc6775ee351519082779', 'cf_clearance': '6f72b46f12e0f5491e84abc94772c48149b768ef-1519082786-86400'}

cookie_final = requests.cookies.merge_cookies(requests.cookies.RequestsCookieJar(), cloudflare_cookies)

print(cookie_final)

你想要什么,cookies.merge_cookies可以将一个cookiejar与一个dict合并