在Python中进行HTTP请求时保持会话

27 投票
3 回答
64796 浏览
提问于 2025-04-15 11:54

我需要写一个Python脚本,向同一个网站发送多个HTTP请求。除非我搞错了(我可能确实搞错了),否则urllib在每次请求时都会重新进行身份验证。由于一些原因,我需要能够只进行一次身份验证,然后在后续的请求中使用这个会话。

我使用的是Python 2.3.4

3 个回答

16

Python 2

如果你使用的是基于cookie的认证,可以用HTTPCookieProcessor

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

如果你使用的是HTTP认证,可以用basic或digest 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')

... 并且在每次请求时都使用同一个打开器。

Python 3

在Python3中,urllib2和cookielib被移到了http.requesthttp.cookiejar

29

使用Requests库。从http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Session对象可以让你在多个请求之间保持某些参数不变。它还可以在从这个Session实例发出的所有请求中保持cookies。

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"}}'
26

如果你想保持登录状态,就需要重复使用那个小饼干(cookie)。我不太确定在 Python 2.3.4 版本中是否可以用 urllib2,但这里有个示例教你怎么做:

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)

撰写回答