python - 获取cookie到期时间使用请求库 [英] python - get cookie expiry time using the requests library

查看:2885
本文介绍了python - 获取cookie到期时间使用请求库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试获取从服务器检索的特定Cookie的到期时间:

I am trying to get the expiry time of a specific cookie that I retrieve from the server as:

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

这将列出服务器发送的所有cookie(我得到2个cookie):

This will list all cookies sent by the server (I get 2 cookies) as:

<<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的到期时间

As you can see, we have two cookies. I would like to get the expiry time of the cookie named "WebSecu"

谢谢

推荐答案

请求中,cookie jar是一个非常特殊的对象。您可能会注意到,如果您这样做:

In requests, the cookie jar is a very special object. You might notice that if you do:

r.cookies['WebSecu']

您将收到该cookie的值作为字符串(在您的示例中 f ) 。要获取包含该信息的实际Cookie对象,您必须遍历cookie jar,如下所示:

You'll receive the value of that cookie as a string (in your example f). To get the actual cookie object that holds that information, you will have to iterate over the cookie jar like so:

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

这篇关于python - 获取cookie到期时间使用请求库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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