I found the following code snippet on my hard drive today. It allows you to access Firefox 3.x cookies in Python. Firefox 3.x moved away from the older text file format to a sqlite database.
This code is useful if you want to access something behind an authentication gateway and you also access the page through your web browser. You can also use this code to convert a sqlite database into a cookie file CURL can read.
I didn’t write this code, it was written by Noah Fontes when we where doing some scraping of the Google Summer of Code website (before I joined Google).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #! /usr/bin/env python # Protocol implementation for handling gsocmentors.com transactions # Author: Noah Fontes nfontes AT cynigram DOT com # License: MIT def sqlite2cookie(filename): from cStringIO import StringIO from pysqlite2 import dbapi2 as sqlite con = sqlite.connect(filename) cur = con.cursor() cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies") ftstr = ["FALSE","TRUE"] s = StringIO() s.write("""\ # Netscape HTTP Cookie File # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. """) for item in cur.fetchall(): s.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( item[0], ftstr[item[0].startswith('.')], item[1], ftstr[item[2]], item[3], item[4], item[5])) s.seek(0) cookie_jar = cookielib.MozillaCookieJar() cookie_jar._really_load(s, '', True, True) return cookie_jar







{ 3 } Comments
You can find the code in an easier to edit format at Mithro’s Useful Bit repository.
There is also code for compressing your sqlite databases and other useful tools.
is the firefox3 sqlite cookie file located in ~/.mozilla/firefox ?
This code is neat and all, but it doesn’t technically show how to read Firefox cookies…
{ 2 } Trackbacks
[…] Python ä¸è¯»å– Firefox 3 çš„ cookie 的代ç ,在 Google Reader 里很快就找到了:Reading Firefox 3.x cookies in Python 。ä¸è¿‡åœ¨é‚£ä¹‹å‰æˆ‘手工把 Firefox çš„ Cookie å¤åˆ¶å‡ºæ¥åŠ åˆ° Python çš„ urllib2 çš„ […]
[…] I wrote about how to reading the cookies from Firefox 3.0 from Python. This code snippet extends the previous example by adding code which finds the cookie […]