The Python Oracle

How to modify cookies in Requests

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 How To Modify Cookies In Requests
01:33 Accepted Answer Score 7
02:10 Answer 2 Score 1
02:18 Thank you

--

Full question
https://stackoverflow.com/questions/2542...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pythonrequests

#avk47



ACCEPTED ANSWER

Score 7


As you can see, your cookie has no domain specified for it, so it's actually another cookie.

Using domain and path

    session.cookies.set('NID', 'abc', domain='.google.co.uk', path='/')

will set new cookie instead of the previously defined one.

RequestCookieJar is a wrapper for cookielib.CookieJar, but if you want to modify cookie attributes in-place (so that you reference the actual cookielib.Cookie objects) I found no better way than to use iterator.

If you look into the sources of requests.cookies.RequestsCookieJar there are just no other methods that let you access items themselves and not their name/value fields.




ANSWER 2

Score 1


For me worked:

for cookie in response.cookies:
    if cookie.name == 'NID':
        cookie.value = 'abc'
        break