使用请求模块,如何处理请求响应中的“set-cookie"? [英] Using requests module, how to handle 'set-cookie' in request response?

查看:45
本文介绍了使用请求模块,如何处理请求响应中的“set-cookie"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开登录页面 (GET),获取网络服务器提供的 cookie,然后提交用户名和密码对以登录站点 (POST).

I'm attempting to open a login page (GET), fetch the cookies provided by the webserver, then submit a username and password pair to log into the site (POST).

看着 这个 Stackoverflow 问题/答案,我认为我只需执行以下操作:

Looking at this Stackoverflow question/answer, I would think that I would just do the following:

import requests
import cookielib


URL1 = 'login prompt page'
URL2 = 'login submission URL'
jar = cookielib.CookieJar()

r = requests.get(URL1, cookies=jar)
r2 = requests.post(URL2, cookies=jar, data="username and password data payload")

然而,在 r 中,头中有一个 set-cookie,但在 jar 对象中并没有改变.事实上,jar 中没有填充任何内容,如链接问题的响应所示.

However, in r there is a set-cookie in the header, but that isn't changing in the jar object. In fact, nothing is being populated into jar as the linked question's response would indicate.

我在我的代码中通过使用 headers dict 来解决这个问题,在执行 GET 或 POST 之后,使用它来处理 set-cookie 标头:

I'm getting around this in my code by having a headers dict and after doing the GET or POST, using this to handle the set-cookie header:

headers['Cookie'] = r.headers['set-cookie']

然后在请求方法中传递标头.这是正确的,还是有更好的方法来应用 set-cookie?

Then passing around the header in the requests methods. Is this correct, or is there a better way to apply the set-cookie?

推荐答案

忽略 cookie-jar,让 requests 为您处理 cookie.改用 会话对象,它会保留 cookie 和将它们发送回服务器:

Ignore the cookie-jar, let requests handle cookies for you. Use a session object instead, it'll persist cookies and send them back to the server:

with requests.Session() as s:
    r = s.get(URL1)
    r = s.post(URL2, data="username and password data payload")

这篇关于使用请求模块,如何处理请求响应中的“set-cookie"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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