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