在发出 HTTP 请求时在 python 中保持会话

编程入门 行业动态 更新时间:2024-10-23 19:22:38
本文介绍了在发出 HTTP 请求时在 python 中保持会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要编写一个 python 脚本来向同一个站点发出多个 HTTP 请求.除非我错了(而且我很可能是错的),否则 urllib 会为每个请求重新进行身份验证.由于我不会讨论的原因,我需要能够进行一次身份验证,然后将该会话用于我的其余请求.

I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests.

我使用的是 python 2.3.4

I'm using python 2.3.4

推荐答案

如果您想保留身份验证,您需要重用 cookie.我不确定 urllib2 是否在 python 2.3.4 中可用,但这里有一个示例:

If you want to keep the authentication you need to reuse the cookie. I'm not sure if urllib2 is available in python 2.3.4 but here is an example on how to do it:

req1 = urllib2.Request(url1) response = urllib2.urlopen(req1) cookie = response.headers.get('Set-Cookie') # Use the cookie is subsequent requests req2 = urllib2.Request(url2) req2.add_header('cookie', cookie) response = urllib2.urlopen(req2)

更多推荐

在发出 HTTP 请求时在 python 中保持会话

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

发布评论

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

>www.elefans.com

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