How to send cookies in a post request with the Python Requests library?
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?
Solution 1:
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 :)
Solution 2:
Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:
import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)