Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cookies in Python Requests

I am trying to login to a page and access another link in the page.

payload={'username'=<username>,'password'=<password>} with session() as s:     r = c.post(<URL>, data=payload)     print r     print r.content 

This is giving me a "405 Not Allowed" error. I checked the post method details using chrome developer tools and could see an api (URL/api/auth). I posted to that URL with the payload and it was working and i was getting a response similar to what i could see in the developer.

Unfortunately when trying to 'get' another url after login, i am still getting the content from the login page. Why is the login not sticking? Should i use cookies? I am a newbie, so i don't really know how to work with cookies.

like image 331
user1474157 Avatar asked Jul 22 '15 05:07

user1474157


People also ask

How do I send a cookie request in Python?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.

How are cookies added to requests?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

How do I set cookies in a POST request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.


1 Answers

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session()  # all cookies received will be stored in the session object  s.post('http://www...',data=payload) s.get('http://www...') 

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

like image 82
gtalarico Avatar answered Sep 29 '22 14:09

gtalarico