Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse requests.session cookie attributes in python

I'm writing a python 3 script to check particular attributes of a cookie on a site I'm working on. I currently authenticate to the site with requests.session:

SiteLogin = 'https://mytestsite.com/login'
payload = {'username': USER, 'password': PASSWORD}
s = requests.session()
s.post(SiteLogin, data=payload)
s.cookies

Now, the cookies have a number of attributes including name, domain, expiration, etc. I wasn't able to find a method to actually expose all of the attributes as a dictionary for a given cookie so that I could parse out the expected values.

Is there a method I missed?

EDIT

Updated to clarify what I'm seeing:

>>> s.cookies
<RequestsCookieJar[Cookie(version=0, name='COOKIE_NAME', value='COOKIE_VALUE', port=None, port_specified=False, domain='DOMAIN, domain_specified=False, domain_initial_dot=False, path='PATH', path_specified=True, secure=True, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
>>> print(s.cookies)
<RequestsCookieJar[<Cookie 'COOKIE_NAME'='COOKIE_VALUE' for DOMAIN+PATH>]>
>>> print(s.cookies.get_dict())
{'COOKIE_NAME': 'COOKIE_VALUE'}

So, lets say I wanted to get the 'expires' value for each cookie (notice above, this is available by running s.cookies). How can I access just the expiry value? If there are many cookies on my system, is it possible to loop through them all, and check the expiry on each?

Something like:

>>> s.cookies['expires']
None
like image 314
Frostbyte Avatar asked Sep 13 '26 07:09

Frostbyte


2 Answers

So in order to just print the cookies you can try implement the following code:

payload = {'username': USER, 'password': PASSWORD}
s = requests.session()
s.post(SiteLogin, data=payload)
list(s.cookies)

hope this helps

like image 159
Nazim Kerimbekov Avatar answered Sep 16 '26 03:09

Nazim Kerimbekov


So, found a solution based on Fozoro's answer. The cookie object within the cookiejar contains the member attributes I was interested in.

payload = {'username': USER, 'password': PASSWORD}
s = requests.session()
s.post(SiteLogin, data=payload)
for cookie in list(s.cookies):
    print(cookie.expires)
like image 37
Frostbyte Avatar answered Sep 16 '26 02:09

Frostbyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!