如何在Python请求中使用Cookie

编程入门 行业动态 更新时间:2024-10-28 08:19:59
本文介绍了如何在Python请求中使用Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试登录页面并访问页面中的另一个链接。

I am trying to login to a page and access another link in the page.

payload={'username'=<username>,'password'=<password>} with session() as s: r = c.post(<URL>, data=payload) print r print r.content

这给我一个 405 Not Allowed错误。 我使用chrome开发人员工具检查了发布方法的详细信息,并且可以看到一个api(URL / api / auth)。 我将带有有效负载的URL发布到该URL,并且该URL正在工作,并且得到的响应类似于在开发人员中看到的响应。

This is giving me a "405 Not Allowed" error. I checked the post method details using chrome developer tools and could see an api (URL/api/auth). I posted to that URL with the payload and it was working and i was getting a response similar to what i could see in the developer.

不幸的是,尝试时登录后获取另一个网址,我仍然从登录页面获取内容。 为什么登录不固定?我应该使用Cookie吗? 我是新手,所以我真的不知道如何使用Cookie。

Unfortunately when trying to 'get' another url after login, i am still getting the content from the login page. Why is the login not sticking? Should i use cookies? I am a newbie, so i don't really know how to work with cookies.

推荐答案

会话对象。它存储cookie,以便您可以发出请求,并为您处理cookie

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() # all cookies received will be stored in the session object s.post('www...',data=payload) s.get('www...')

文档: requests.readthedocs.io/en/master/user/advanced/#session-objects

您还可以将cookie数据保存到外部文件,然后重新加载它们以保持会话持久性,而不必每次运行脚本时都登录:

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

如何保存向文件请求(python)cookie?

更多推荐

如何在Python请求中使用Cookie

本文发布于:2023-11-23 09:25:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Python   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!