The Python Oracle

How to modify cookies in Requests

This video explains
How to modify cookies in Requests

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
06:49 Accepted answer (Score 7)
07:33 Answer 2 (Score 1)
07:47 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