python - 使用requests库获取cookie过期时间

5 投票
1 回答
13040 浏览
提问于 2025-04-17 23:24

我正在尝试获取从服务器获取的一个特定cookie的过期时间,代码如下:

s = requests.session()
r = s.get("http://localhost/test")
r.cookies

这段代码会列出服务器发送的所有cookies(我得到了两个cookie),结果如下:

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie PHPSESSID=cusa6hbtb85li8po
argcgev221 for localhost.local/>, <Cookie WebSecu=f for localhost.local/test>]>

当我执行:

r.cookies.keys

我得到的结果是:

<bound method RequestsCookieJar.items of <<class 'requests.cookies.RequestsCooki
eJar'>[Cookie(version=0, name='PHPSESSID', value='30tg9vn9376kmh60ana2essfi3', p
ort=None, port_specified=False, domain='localhost.local', domain_specified=False
, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires
=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False), Co
okie(version=0, name='WebSecu', value='f', port=None, port_specified=False, doma
in='localhost.local', domain_specified=False, domain_initial_dot=False, path='/test', path_specified=False, secure=False, expires=1395491371, discard=Fals
e, comment=None, comment_url=None, rest={}, rfc2109=False)]>>

如你所见,我们有两个cookie。我想获取名为“WebSecu”的cookie的过期时间。

谢谢你

1 个回答

13

requests这个库里,cookie jar(饼干罐)是一个很特别的东西。你可能会注意到,如果你这样做:

r.cookies['WebSecu']

你会得到那个cookie的值,作为一个字符串(在你的例子里是f)。但如果你想获取实际存储这些信息的cookie对象,你就需要像这样遍历饼干罐:

expires = None
for cookie in r.cookies:
    if cookie.name == 'WebSecu':
        expires = cookie.expires

撰写回答