在Python中访问Firefox 3的Cookie

3 投票
3 回答
4438 浏览
提问于 2025-04-16 09:26

我正在尝试写一个Python脚本,想要用Firefox里的cookies去访问一个网站。如果支持Firefox 3的话,cookielib.MozillaCookieJar会很好用。请问有没有办法在Python里访问Firefox 3的cookies?

我发现,在[home]/.mozilla/firefox/[随机字母].default/文件夹下,有两个文件,分别叫做cookies.sqlite和cookies-nontor.xml。看起来.xml文件比较简单,应该可以写个函数从中提取出CookieJar,但如果已经有现成的模块可以做到这一点,那我就不想重复造轮子了。

3 个回答

1

TryPyPy的回答让我找到了正确的方向,但链接中的代码已经过时,无法在Python3上运行。这里有一段Python3的代码,可以从正在运行的Firefox浏览器中读取cookie,并在查询网页时使用这些cookie:

import requests

url = 'http://github.com'
cookie_file = '/home/user/.mozilla/firefox/f00b4r.default/cookies.sqlite'



def get_cookie_jar(filename):
    """
    Protocol implementation for handling gsocmentors.com transactions
    Author: Noah Fontes nfontes AT cynigram DOT com
    License: MIT
    Original: http://blog.mithis.net/archives/python/90-firefox3-cookies-in-python

    Ported to Python 3 by Dotan Cohen
    """

    from io import StringIO
    import http.cookiejar
    import sqlite3

    con = sqlite3.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 = http.cookiejar.MozillaCookieJar()
    cookie_jar._really_load(s, '', True, True)

    return cookie_jar



cj = get_cookie_jar(cookie_file)
response = requests.get(url, cookies=cj)
print(response.text)

这段代码在Kubuntu Linux 14.10上经过测试,使用的是Python 3.4.2和Firefox 39.0。代码也可以在我的Github仓库找到。

1

我创建了一个模块,可以从Firefox浏览器中加载cookies,具体内容可以在这里找到:https://bitbucket.org/richardpenman/browser_cookie/

使用示例:

import requests
import browser_cookie
cj = browser_cookie.firefox()
r = requests.get(url, cookies=cj)
2

这里有一个教程,教你如何在Firefox 3中访问SQLite格式的cookies。还有一个补丁可以在Python的错误追踪网站找到,同时Mechanize也支持这个功能。

撰写回答