Python:如何在请求中使用Chrome Cookie [英] Python: How to use Chrome cookies in requests
问题描述
我正在寻找一种方法,可以从chrome浏览器中获取Cookie(默认),并通过请求使用它.
I am searching for a method to get my cookies from my chrome browser (default), and use it using requests.
我当然已经搜索了,例如发现了这个. 如何使用Python从网络浏览器中获取Cookie? 但这不再起作用,因为Chrome一直在更新.他们在答案中命名的模块上一次在2016年进行了测试.
I have ofcourse already searched around, and found for example this; How to get cookies from web-browser with Python? But that does not work anymore, because Chrome keeps on updating. And the modules they name in the answer were last tested in 2016.
所以,他们在答案中给出的代码是+我多余的东西,使饼干回来了
So, the code they gave at the answer was + my extra stuff to get the cookies back
import win32crypt
import browsercookie
import requests
session = requests.Session()
cj = browsercookie.chrome()
r = session.get("https://stackoverflow.com/", cookies=cj)
print session.cookies.get_dict()
但是当我运行它时(在我的浏览器中登录到stackoverflow时),它返回{}
.那不是很多(不是我想要的结果)
But when I run this (while being logged into stackoverflow on my browser), it return {}
. And that's not alot (not the result I was loking for)
推荐答案
我有一个很好的脚本,可以直接在/Default/Cookies 上读取Chrome cookie.我想你会没事的.
I have a good script to read Chrome cookies directly on /Default/Cookies. I think you would work fine.
import sqlite3
import sys
from os import getenv, path
import os
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
import keyring
def get_cookies(url, cookiesfile):
def chrome_decrypt(encrypted_value, key=None):
dec = AES.new(key, AES.MODE_CBC, IV=iv).decrypt(encrypted_value[3:])
decrypted = dec[:-dec[-1]].decode('utf8')
return decrypted
cookies = []
if sys.platform == 'win32':
import win32crypt
conn = sqlite3.connect(cookiesfile)
cursor = conn.cursor()
cursor.execute(
'SELECT name, value, encrypted_value FROM cookies WHERE host_key == "' + url + '"')
for name, value, encrypted_value in cursor.fetchall():
if value or (encrypted_value[:3] == b'v10'):
cookies.append((name, value))
else:
decrypted_value = win32crypt.CryptUnprotectData(
encrypted_value, None, None, None, 0)[1].decode('utf-8') or 'ERROR'
cookies.append((name, decrypted_value))
elif sys.platform == 'linux':
my_pass = 'peanuts'.encode('utf8')
iterations = 1
key = PBKDF2(my_pass, salt, length, iterations)
conn = sqlite3.connect(cookiesfile)
cursor = conn.cursor()
cursor.execute(
'SELECT name, value, encrypted_value FROM cookies WHERE host_key == "' + url + '"')
for name, value, encrypted_value in cursor.fetchall():
decrypted_tuple = (name, chrome_decrypt(encrypted_value, key=key))
cookies.append(decrypted_tuple)
else:
print('This tool is only supported by linux and Mac')
conn.close()
return cookies
if __name__ == '__main__':
pass
else:
salt = b'saltysalt'
iv = b' ' * 16
length = 16
#get_cookies('YOUR URL FROM THE COOKIES', 'YOUR PATH TO THE "/Default/Cookies" DATA')
这篇关于Python:如何在请求中使用Chrome Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!