Python 使用请求模块,如何处理请求响应中的“set-cookie”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21736970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:30:27  来源:igfitidea点击:

Using requests module, how to handle 'set-cookie' in request response?

pythonpython-2.7cookiespython-requests

提问by tommy_o

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

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

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

看看这个 Stackoverflow question/answer,我认为我会做以下事情:

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

However, in rthere is a set-cookiein the header, but that isn't changing in the jarobject. In fact, nothing is being populated into jaras the linked question's response would indicate.

但是,在标题中r有一个set-cookie,但在jar对象中并没有改变。事实上,jar正如链接问题的回答所表明的那样,没有填充任何内容。

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-cookieheader:

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

headers['Cookie'] = r.headers['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?

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

采纳答案by Martijn Pieters

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

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

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

回答by TankorSmash

There's an included class called a sessionwhich automatically handles this sort of thing for you. You can create an instance of it, and then call getand setright on that instance instead.

有一个名为 a 的包含类session,它会自动为您处理此类事情。您可以创建它的一个实例,然后在该实例上调用getand setright。

import requests

URL1 = 'login prompt page'
URL2 = 'login submission URL'

session = requests.Session()

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

回答by Marcus Junius Brutus

Another way that has worked for me (without using session objects) is the following (tested in v2.18.4).

另一种对我有用的方法(不使用会话对象)如下(在 中测试v2.18.4)。

jar = requests.cookies.RequestsCookieJar()
response1 = requests.get(some_url, cookies=jar) # or post ...
jar.update(response1.cookies)
response2 = requests.get(some_other_url, cookies=jar) # or post ...

Note that the above code will fail in the presence of redirects which are handled transparently by the Requestslibrary. In such a case, you also have to update your jar with the cookies sent in the redirect responses. E.g. by doing something like the following:

请注意,如果存在由Requests库透明处理的重定向,上述代码将失败。在这种情况下,您还必须使用重定向响应中发送的 cookie 更新您的 jar。例如,通过执行以下操作:

if (response.history): # we have to add to the cookie jar, the cookies sent by the server in intermediate responses 
    for historicResponse in response.history:
        jar.update(historicResponse.cookies)