我需要编写一个 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 中保持会话
发布评论