Fix Python – How to send cookies in a post request with the Python Requests library?

Question

Asked By – Ricardo Altamirano

I’m trying to use the Requests library to send cookies with a post request, but I’m not sure how to actually set up the cookies based on its documentation. The script is for use on Wikipedia, and the cookie(s) that need to be sent are of this form:

enwiki_session=17ab96bd8ffbe8ca58a78657a918558e; path=/; domain=.wikipedia.com; HttpOnly

However, the requests documentation quickstart gives this as the only example:

cookies = dict(cookies_are='working')

How can I encode a cookie like the above using this library? Do I need to make it with python’s standard cookie library, then send it along with the POST request?

Now we will see solution for issue: How to send cookies in a post request with the Python Requests library?


Answer

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy 🙂

This question is answered By – Kenneth Reitz

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0