问题
I'm trying to make a python script that will access a website with the cookies in Firefox. cookielib.MozillaCookieJar would work if it supported Firefox 3. Is there a way to access Firefox 3 cookies inside of python?
I see that there are two files under [home]/.mozilla/firefox/[randomletters].default/ called cookies.sqlite and cookies-nontor.xml. The .xml file looks like it would be easy to write a function that will return a CookieJar from it, but if there's already a module that does this, then I'd like to avoid re-inventing the wheel.
回答1:
Here's a recipe for accessing the SQLite cookies in FF 3. There's a patch at the Python bug Tracker and Mechanize also supports this.
回答2:
I created a module to load cookies from Firefox, available here: https://bitbucket.org/richardpenman/browser_cookie/
Example usage:
import requests
import browser_cookie
cj = browser_cookie.firefox()
r = requests.get(url, cookies=cj)
回答3:
TryPyPy's answer got me on the right track, but the code in the linked recipe was outdated and would not work with Python3. Here is Python3 code that will read the cookie jar from a running Firefox and use it when querying web pages:
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)
Tested on Kubuntu Linux 14.10 with Python 3.4.2 and Firefox 39.0. The code is also available from my Github repo.
来源:https://stackoverflow.com/questions/4602048/accessing-firefox-3-cookies-in-python