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

Hec*_*out 26 python authentication http

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

我正在使用python 2.3.4

Pio*_*ost 29

使用请求库.来自http://docs.python-requests.org/en/latest/user/advanced/#session-objects:

Session对象允许您跨请求保留某些参数.它还会在从Session实例发出的所有请求中保留cookie.

s = requests.session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'
Run Code Online (Sandbox Code Playgroud)


Nad*_*mli 25

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

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)
Run Code Online (Sandbox Code Playgroud)

  • 这并不像你所说的那么简单.当您找到此语句时,请参阅RFC 6265,*5.4 Cookie标头**用户代理必须使用等效于以下算法的算法来计算cookie存储中的"cookie-string"和request-uri:*with以下算法. (2认同)

lis*_*ine 16

Python 2

如果这是基于cookie的身份验证,请使用HTTPCookieProcessor:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
Run Code Online (Sandbox Code Playgroud)

如果这是HTTP身份验证,请使用基本或摘要AuthHandler:

import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
Run Code Online (Sandbox Code Playgroud)

...并为每个请求使用相同的开启者.

Python 3

在Python3中,urllib2和cookielib分别被移动到http.requesthttp.cookiejar.