如何用Python从网页浏览器获取cookies?
背景:
我正在为一个OpenID消费者(实际上是StackExchange)开发后端访问。如果我想给用户提供所有可能的OpenID提供者作为选项,那么我就得模拟浏览器的操作,先登录到每一个提供者那里,然后才能提交OpenID网址。不过,我觉得我可以简化这个过程,直接使用用户浏览器里现有的cookies,直接用网址请求认证。
问题:
我该如何访问用户浏览器里的cookies?我在网上看到关于如何用Python做到这一点的信息很少。这个之前的问题部分回答了关于Firefox的问题,特别提到了下面的代码示例。不过,我需要访问在Linux上最常用的浏览器的cookies,而不仅仅是Firefox。
#! /usr/bin/env python
# Protocol implementation for handling gsocmentors.com transactions
# Author: Noah Fontes nfontes AT cynigram DOT com
# License: MIT
def sqlite2cookie(filename):
from cStringIO import StringIO
from pysqlite2 import dbapi2 as sqlite
con = sqlite.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 = cookielib.MozillaCookieJar()
cookie_jar._really_load(s, '', True, True)
return cookie_jar
问题:Python有没有提供一个模块,可以帮助从浏览器提取cookies?如果没有,我该如何调整上面的代码,以便从其他浏览器(比如Chromium等)提取cookies?
附注:或者我是不是在错误的方向上看待最初的问题(也就是,如何认证到OpenID提供者)?(我觉得我只是把一个问题换成了另一个问题。)
2 个回答
0
除了browser-cookie3,你还可以试试这个链接:https://github.com/n8henrie/pycookiecheat -- 在2021年4月的时候,我在Ubuntu 20.04的Chrome上用这个是有效的。
35
我创建了一个模块来完成这个功能,可以在这里找到:https://bitbucket.org/richardpenman/browsercookie/
使用示例:
import requests
import browsercookie
cj = browsercookie.chrome()
r = requests.get('http://stackoverflow.com', cookies=cj)
python3 分支: https://github.com/borisbabic/browser_cookie3