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

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

问题描述

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



查看这个Stackoverflow问题/ answer ,我认为我只会做以下:

 导入请求
import cookielib


URL1 ='登录提示页'
URL2 ='登录提交URL'
jar = cookielib.CookieJar()

r = requests.get(URL1,cookies = jar)
r2 = requests.post(URL2,cookies = jar,data =用户名和密码数据有效负载)
r 中有一个 set-cookie ,但是在 jar 对象中不会改变。事实上,没有什么被填充到 jar 作为链接问题的响应将指示。



这在我的代码中有一个headers dict和做完GET或POST后,使用它来处理 set-cookie 头:

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

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

解决方案

忽略cookie-jar,让请求为您处理cookie。使用会话对象,它将保留Cookie并将其发回到服务器:

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


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

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

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.

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

Then passing around the header in the requests methods. Is this correct, or is there a better way to apply the set-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天全站免登陆