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獲得。
感謝您的回覆!有沒有使用機械化來獲取瀏覽器cookies的例子?我在舊cookies.txt的文檔中看到了一個示例,但未看到新的cookies.sqlite。 – Hempage 2011-01-05 16:55:13
我能夠找到這個早期的解釋:http://osdir.com/ml/python.wwwsearch.general/2008-02/msg00012.html – TryPyPy 2011-01-05 23:06:08
機械化嘗試了很久之後,我沒有運氣......但是在使用你鏈接的食譜,我已經取得了巨大的成功。 – Hempage 2011-01-06 23:26:26