-1

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)  
2
  • 3
    you're sending the cookie to the server but trying to print the server's cookies in response. Your custom cookie won't be returned by the server since it's only part of the request, not the server's response. Commented Aug 15, 2024 at 12:52
  • Okay. How do I fix that?@Michael Commented Aug 16, 2024 at 9:28

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.