在Python中访问firefox3 cookies

2024-09-30 22:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个python脚本,它将使用Firefox中的cookies访问一个网站。cookielib.MozillaCookieJar公司如果支持firefox3就可以了。有没有办法在python中访问firefox3cookies?在

我看到在[home]/.mozilla/firefox/[randomletters].default/called下有两个文件cookies.sqlite还有饼干-非标记.xml. xml文件看起来很容易编写一个从中返回CookieJar的函数,但是如果已经有一个模块可以这样做,那么我希望避免重新发明轮子。在


Tags: 文件脚本mozillahome网站公司xmlfirefox
3条回答

下面是a recipe用于访问FF3中的SQLite cookies。在Python bug Tracker和{a3}上有一个补丁也支持这一点。在

TryPyPy's answer让我走上了正确的轨道,但是链接配方中的代码已经过时,不能与Python3一起使用。以下是Python3的Python3代码,它将从运行的Firefox中读取cookiejar并在查询网页时使用它:

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)

在KubuntuLinux14.10和Python3.4.2和Firefox39.0上进行了测试。代码也可以从my Github repo获得。在

我创建了一个从Firefox加载cookies的模块,可以在这里找到:https://bitbucket.org/richardpenman/browser_cookie/

用法示例:

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

相关问题 更多 >