4

I tried searching for couple of hours, but nothing seem to be working. I am trying to login to a webpage to download some data. Each login requires a new cookie (PHPSESSID) since it expires when browsing connection ends. I tried the following:

import requests

payload = {'user':'myusername', 'password':'mypassword'}
url = 'blahblah.blah'

with requests.Session() as s:
    r = s.get(url)
    cookie = {'PHPSESSID': r.cookies['PHPSESSID']}
    r = s.post(url, data=payload, cookies=cookie)

This, however, redirects to the login page, which I think means the login failed. I then tried to login through Chrome, and obtain the cookie manually. When I do this, I can use that cookie to login using requests.

with requests.Session() as s:
    cookie = {'PHPSESSID': 'some value obtained by logging in through Chrome and copying the cookie value'}
    r = s.post(url, cookies=cookie, data=payload)

The above works perfectly fine.

Im not sure what Im doing incorrectly in the original code. Any assistance is appreciated!

onepint16oz
  • 294
  • 3
  • 12
  • The point of using Requests sessions is that the cookies are sent back automatically, on successive requests. How about you don't set the cookie yourself. or Set using s.cookies – dhishan Dec 27 '16 at 19:28
  • I tried it without setting the cookie manually, but it didn't work. Still redirects to login page. – onepint16oz Dec 27 '16 at 19:45
  • Maybe use Wireshark tool to analyze the cookie received and sent by the server and check the cookie assigned by `cookie = {'PHPSESSID': r.cookies['PHPSESSID']}` and check for r.status or r.history by running this code in interpreter. The code looks fine to me actually. – dhishan Dec 27 '16 at 20:04
  • 1
    as @dhishan said, u don't have to set cookie manually. It would be helpful if u mention what URL you are trying to login. Username and Password are not the only fields that get posted while logging into some sites. – krishh Dec 28 '16 at 14:35

1 Answers1

3
import requests

payload = {'user':'myusername', 'password':'mypassword'}
url = 'blahblah.blah'

with requests.Session() as s:
    r = s.post(url, data=payload)
    cookie = {'PHPSESSID': requests.utils.dict_from_cookiejar(s.cookies)['PHPSESSID']}

After which, you can use your cookie for subsequent requests You are logging in, I think it should be a post request you should be making.

Master p
  • 826
  • 9
  • 8