pythonhttppython-requestssetcookie

How can I set cookies using python requests


I am trying to access the cookies of websites, take Wikipedia for example and change their values. I also want to create cookies of my own and put them into my website. For some reason, which I'm not able to understand by myself, the cookies won't be saved/inserted properly

I've tried the following code:

import pip._vendor.requests as requests

my_cookie = {"new_cookie" : "new_value"}

response = requests.get("https://wikipedia.com", cookies=my_cookie)

print(response.cookies)

What I expected was a list of the previous cookies and the "new_cookie" as well, but is wasn't added. Could anyone please explain why and what I should have done instead? I have also tried the following without any results:

import pip._vendor.requests as requests

with requests.Session() as http_session:
    requests.session().cookies.set("my_cookie", "my_val", domain="https://wikipedia.com")

    r = http_session.get("https://wikipedia.com")
    print(r.cookies)  

Solution

  • As mentioned in the above comment, your custom cookie won't be returned by the server since it's only included in the request, not in the server's response. However, if you need to add your custom cookie to the cookies received from the server, you can do so manually after receiving the response:

    import pip._vendor.requests as requests
    
    response = requests.get("https://wikipedia.com")
    response.cookies.set("my_cookie", "my_val", domain="wikipedia.com")
    print(response.cookies)