简体   繁体   English

Python:请求会话登录Cookie

[英]Python: Requests Session Login Cookies

My intention is to log into a site and then access a protected image from a python script. 我的目的是登录一个站点,然后从python脚本访问受保护的图像。 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. 我确信我可以成功登录,因为我之后已经下载了html文件,并且它是以登录的形式。但我的问题是在我看来我的PHPSESSID cookie没有通过所以我得到403错误。 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. 我也尝试手动将cookie添加到我的"r_img"行,它没有任何区别,我仍然得到一个空的CookieJar403错误。 Would this be not possible with only the requests modul? 只有请求模块才能实现这一点吗? Did I overlook something? 我忽略了什么吗? Excuse me for being not quite familiar with HTTP requests. 请原谅我对HTTP请求不太熟悉。

I'm using Python 3.4 just for sake of clarity. 我只是为了清晰起见而使用Python 3.4。

You are passing in your form data as HTTP headers . 您将表单数据作为HTTP标头传递。 A POST login form should send form elements as the data parameter instead: POST登录表单应该将表单元素作为data参数发送:

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". 您的POST请求被服务器接受( 200 OK ),但由于没有发布登录信息, 主体很可能会告诉您“登录不正确,请再试一次”。

The server most likely cleared the cookie again seeing as it was not a valid login session when you requested the image. 当您请求图像时,服务器很可能再次清除cookie,因为它不是有效的登录会话。 The 403 response probably contains a Set-Cookie header for PHPSESSID with a date in the past to clear it. 403响应可能包含PHPSESSIDSet-Cookie标头,其中包含过去的日期以清除它。

Try doing it like this: 尝试这样做:

As per python-requests docs: 根据python-requests文档:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM