Python:请求会话登录 Cookie [英] Python: Requests Session Login Cookies

查看:30
本文介绍了Python:请求会话登录 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是登录一个站点,然后从 python 脚本访问受保护的图像.我可以通过浏览器进行合法访问和工作访问.

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.

这就是我现在拥有的.

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'])

输出:

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

我确定我可以成功登录,因为我这样做后曾经下载过html文件,并且是登录的形式.但我的问题是在我看来我的PHPSESSID cookie 没有通过,所以我收到一个 403 错误.但我显然在我的会议上有它.我还尝试将 cookie 手动添加到我的 "r_img" 行,但没有任何区别,我仍然得到一个空的 CookieJar 和一个 403 错误回复.仅使用请求模块是不可能的吗?我忽略了什么吗?原谅我不太熟悉 HTTP 请求.

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.

为了清楚起见,我使用 Python 3.4.

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

推荐答案

您将表单数据作为HTTP标头传递.POST 登录表单应该将表单元素作为 data 参数发送:

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': '***' })

检查返回的正文,而不仅仅是状态代码.您的 POST 请求已被服务器接受 (200 OK) 但由于未发布登录信息,正文 很可能会告诉您诸如登录不正确,请重试"之类的信息".

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".

服务器很可能再次清除了 cookie,因为当您请求图像时它不是有效的登录会话.403 响应可能包含 PHPSESSIDSet-Cookie 标头,并带有过去的日期以清除它.

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.

这篇关于Python:请求会话登录 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆