Skip to content

Reading Firefox 3.x cookies in Python

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

#! /usr/bin/env python
# Protocol implementation for handling 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()
# Netscape HTTP Cookie File
# 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]))
    cookie_jar = cookielib.MozillaCookieJar()
    cookie_jar._really_load(s, '', True, True)
    return cookie_jar

{ 3 } Comments

  1. mithro | May 15, 2009 at 11:09 am | Permalink

    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.

  2. jake | May 27, 2009 at 11:24 pm | Permalink

    is the firefox3 sqlite cookie file located in ~/.mozilla/firefox ?

  3. Chris | September 21, 2009 at 1:28 pm | Permalink

    This code is neat and all, but it doesn’t technically show how to read Firefox cookies…

{ 2 } Trackbacks

  1. […] Python 中读取 Firefox 3 çš„ cookie 的代码,在 Google Reader 里很快就找到了:Reading Firefox 3.x cookies in Python 。不过在那之前我手工把 Firefox çš„ Cookie 复制出来加到 Python çš„ urllib2 çš„ […]

  2. […] 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 […]

Post a Comment

Your email is never published nor shared. Required fields are marked *