Python: how to dump cookies of a mechanize.Browser instance?
Asked Answered
R

3

11

I am learning how to use mechanize, a Python module to automate interacting with websites.

One feature is the automated handling of cookies. I would to want to dump cookies from a mechanize.Browser instance for debugging purposes, but I can't seem to figure this out myself.

Reprise answered 3/3, 2009 at 11:47 Comment(0)
U
22

>>> from mechanize import Browser
>>> b = Browser()
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[]
>>> b.open('http://google.com')
response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224
>>>
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[Cookie(version=0, name='PREF', value='ID=57d545c229b4cf3f:TM=1236081634:LM=1236081634:S=p001WJMOr-V8Rlvi', port=None, port_specified=False, domain='.google.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153634, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='PREF', value='ID=20534d80a5ccf2ea:TM=1236081635:LM=1236081635:S=jW3UotZ0dg8sv6mf', port=None, port_specified=False, domain='.google.com.ua', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153635, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]
>>>                           

Urano answered 3/3, 2009 at 12:2 Comment(0)
P
5

Just print the CookieJar Instance

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Dump
print cj
Proudfoot answered 23/12, 2014 at 18:43 Comment(2)
What is your question? What problem are you facing?Bruell
This answer is more appropriate. In the accepted answer, the _ prefix in Browser._ua_handlers suggests that it is not part of mechanize public API.Vascular
O
1

Mykolas' answer almost gave me what I was looking for. I was looking for how to save the cookie to a file. Since this answer gives margin to dumping the cookie into a file, maybe it is going to be useful for other people coming here looking for that. To save the cookie to a file:

br._ua_handlers['_cookies'].cookiejar.save("cookie.txt", ignore_discard=True, ignore_expires=True)
Oceanus answered 26/1, 2014 at 22:18 Comment(1)
CookieJar instance has no attribute 'save'Boughten

© 2022 - 2024 — McMap. All rights reserved.