在发出 HTTP 请求时在 python 中保持会话 [英] Keeping a session in python while making HTTP requests

查看:22
本文介绍了在发出 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 中保持会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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