在python保持一个会话,同时使HTTP请求 [英] Keeping a session in python while making HTTP requests

查看:770
本文介绍了在python保持一个会话,同时使HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个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)

这篇关于在python保持一个会话,同时使HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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