2011-01-05 28 views
3

我正在试图制作一个python脚本,它将使用Firefox中的cookie访问网站。 cookielib.MozillaCookieJar会工作,如果它支持Firefox 3.有没有办法访问python内的Firefox 3饼干?在Python中访问Firefox 3 Cookie

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

回答

2

这里的a recipe用于访问FF3中的SQLite cookie。在Python bug TrackerMechanize也有一个补丁支持这个。

+0

感谢您的回复!有没有使用机械化来获取浏览器cookies的例子?我在旧cookies.txt的文档中看到了一个示例,但未看到新的cookies.sqlite。 – Hempage 2011-01-05 16:55:13

+0

我能够找到这个早期的解释:http://osdir.com/ml/python.wwwsearch.general/2008-02/msg00012.html – TryPyPy 2011-01-05 23:06:08

+0

机械化尝试了很久之后,我没有运气......但是在使用你链接的食谱,我已经取得了巨大的成功。 – Hempage 2011-01-06 23:26:26

1

TryPyPy's answer让我在正确的轨道上,但在联配方的代码已经过时,将不适用于Python3。这里是Python3查询代码的网页时,会从运行Firefox读取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。该代码也可从my Github repo获得。