Python: Requests Session Login Cookies

2019-04-29 08:25发布

问题:

My intention is to log into a site and then access a protected image from a python script. I have both legal and working access from a browser.

This is what I have now.

import requests

s = requests.Session()

s.get('*domain*')

r_login  =s.post('*domain*/user.php', headers={'cmd': 'login', 'loginname': '***', 'password': '***' })

print (s.cookies)
print (r_login.status_code)

r_img = s.get('*domain*/*protectedimage*.jpg')
print (r_img.status_code)
print (r.cookies)

print (s.cookies['PHPSESSID'])

Output:

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie PHPSESSID=664b0842085b847a04d415a22e013ad8 for *domain*/>]>
200
403
<<class 'requests.cookies.RequestsCookieJar'>[]>
664b0842085b847a04d415a22e013ad8

I am sure I can successfully log in, because I have once downloaded the html file after doing so, and it was in a form of being logged in. But my problem is that it seems to me that my PHPSESSID cookie does not pass so I get a 403 error back. But I clearly have it in my session. I have also tried adding the cookie manually to my "r_img" line, and it made no difference, I still get an empty CookieJar and a 403 error back. Would this be not possible with only the requests modul? Did I overlook something? Excuse me for being not quite familiar with HTTP requests.

I'm using Python 3.4 just for sake of clarity.

回答1:

You are passing in your form data as HTTP headers. A POST login form should send form elements as the data parameter instead:

r_login = s.post('*domain*/user.php', 
                 data={'cmd': 'login', 'loginname': '***', 'password': '***' })

Do inspect the returned body, not just the status code. Your POST request was accepted by the server (200 OK) but since no login information was posted, the body will most likely tell you something like "login incorrect, please try again".

The server most likely cleared the cookie again seeing as it was not a valid login session when you requested the image. The 403 response probably contains a Set-Cookie header for PHPSESSID with a date in the past to clear it.



回答2:

Try doing it like this:

As per python-requests docs:

payload = {'cmd': 'login', 'loginname': '***', 'password': '***'}
url = '*domain*/user.php'
s.post(url, data=payload)