Posts

Showing posts from December 5, 2014

Serializing that convoluted cookielib.CookieJar

The Python cookielib.CookieJar object is a very convenient feature to manage cookies automatically as you traverse a series of Http web requests back and forth. However, the data structure of the class is a convoluted collection of Python dict . cookielib.CookieJar has a _cookies property which is a dictionary of a dictionary of a dictionary of cookielib.Cookie . To understand the data structure in the CookieJar object cj , try: for domain in cj._cookies.keys(): for path in cj._cookies[domain]: for name in cj._cookies[domain][path]: cookie = cj._cookies[domain][path][name] print domain, path, cookie.name, '=' , cookie.value However, the class-defined __iter__ method makes the above effort unnecessary if you just want to find the value of a cookie. The __iter__ method returns a cookielib.Cookie object for each iteration. You can simply go: for cookie in cj: print cookie.domain, cookie.path, cookie.name, cookie.value # etc I