3

我正在尝试制作一个 python 脚本,该脚本将使用 Firefox 中的 cookie 访问网站。如果 cookielib.MozillaCookieJar 支持 Firefox 3,它会起作用。有没有办法在 python 中访问 Firefox 3 cookie?

我看到 [home]/.mozilla/firefox/[randomletters].default/ 下有两个文件,分别称为 cookies.sqlite 和 cookies-nontor.xml。.xml 文件看起来很容易编写一个从中返回 CookieJar 的函数,但如果已经有一个模块可以做到这一点,那么我想避免重新发明轮子。

4

3 回答 3

2

这是在 FF 3 中访问 SQLite cookie的秘诀。Python bug Tracker上有一个补丁,Mechanize也支持这个。

于 2011-01-05T08:33:38.570 回答
1

我创建了一个从 Firefox 加载 cookie 的模块,可在此处获得:https ://bitbucket.org/richardpenman/browser_cookie/

示例用法:

import requests
import browser_cookie
cj = browser_cookie.firefox()
r = requests.get(url, cookies=cj)
于 2015-04-14T13:13:31.130 回答
1

TryPyPy 的回答让我走上了正轨,但链接配方中的代码已经过时,不适用于 Python3。这是Python3代码,它将从正在运行的 Firefox 中读取 cookie jar,并在查询网页时使用它:

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)

在带有 Python 3.4.2 和 Firefox 39.0 的 Kubuntu Linux 14.10 上进行了测试。该代码也可以从我的 Github repo获得。

于 2015-10-12T10:14:05.107 回答