python - get cookie expiry time using the requests library

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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

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>]>

When I do:

r.cookies.keys

I get:

<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)]>>

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

Thank you

回答1:

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

r.cookies['WebSecu']

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!