简体   繁体   中英

Trying to load cookie into requests session from dictionary

I'm working with the python requests library. I am trying to load a requests session with a cookie from a dictionary:

cookie = {'name':'my_cookie','value': 'kdfhgfkj' ,'domain':'.ZZZ.org', 'expires':'Fri, 01-Jan-2020 00:00:00 GMT'}

I've tried:

s.cookies.set_cookie(cookie)

but this gives:

File "....lib\site-packages\requests\cookies.py", line 298, in set_cookie
    if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
AttributeError: 'dict' object has no attribute 'value'

What am I doing wrong?

cookies has a dictionary-like interface, you can use update() :

s.cookies.update(cookie)

Or, just add cookies to the next request:

session.get(url, cookies=cookie)

It would "merge" the request cookies with session cookies and the newly added cookies would be retained for subsequent requests, see also:

this doesn't seem to work for me for multiple cookies, they just get overwritten so the last one to get added is the only cookie in the jar.

For example, my multiple cookies (from Flaresolverr (which I believe is the same output as selenium)) outputs multiple dictionaries in a list, eg:

cookies = [
      {
        "name": "ASP.NET_SessionId",
        "value": "SOMEVALUE",
        "domain": "my.domain.co.uk",
        "path": "/",
        "expires": -1,
        "size": 41,
        "httpOnly": true,
        "secure": false,
        "session": true
      },
      {
        "name": "__cfduid",
        "value": "SOMEVALUE",
        "domain": ".mydomain.co.uk",
        "path": "/",
        "expires": 1622898293.967355,
        "size": 51,
        "httpOnly": true,
        "secure": true,
        "session": false,
        "sameSite": "Lax"
      }
   ]

So if I then try to add them all in a cookie jar, you can see " __cfduid " is the only cookie in the jar:

r = requests.session()
for c in cookies:
      r.cookies.update(c)

print(r.cookies)
<RequestsCookieJar[<Cookie domain=.mydomain.co.uk for />, <Cookie expires=1622898293.967355 for />, <Cookie httpOnly=True for />, <Cookie name=__cfduid for />, <Cookie path=/ for />, <Cookie sameSite=Lax for />, <Cookie secure=True for />, <Cookie session=False for />, <Cookie size=51 for />, <Cookie value=SOMEVALUE for />]>

I've also tried jar = requests.cookies.RequestsCookieJar() and jar.set(xxxx) but it doesn't like non-standard cookie attributes (eg httpOnly)

Any help would be very much appreciated, thank you!

session.cookies.set_cookie 's parameter should be Cookie object , NOT dict (of cookie)

if you want add new cookie into session.cookies from dict, you can use:

or

more detail pls refer to my another post's answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM