2011-01-05 29 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獲得。