引用not getting all cookie info using python requests module
OP在Chrome上设置了许多cookie,但在他的Python请求代码中没有看到大多数这些cookie。给出的原因是“正在设置的cookie来自其他页面/资源,可能由JavaScript代码加载。”
这是我用来尝试获取访问URL时加载的cookie的函数:
from requests import get from requests.exceptions import RequestException from contextlib import closing def get_cookies(url): """ Returns the cookies from the response of `url` when making a HTTP GET request. """ try: s = Session() with closing(get(url, stream=True)) as resp: return resp.cookies except RequestException as e: print('Error during requests to {0} : {1}'.format(url, str(e))) return None
但是使用这个功能,我只看到由URL设置的cookie,而不是其他像广告cookie。鉴于此设置,如何查看其他Cookie,与Chrome看到的完全一样?即如何在发出GET请求时查看所有cookie,包括来自其他页面/资源的cookie?
做了一些工作,但我设法让它工作。基本上需要硒和铬来实际加载网站和所有第三方的东西。其中一个输出是./chrome_dir/Default/Cookies
中的一个sqlite3数据库数据库,您只需获取自己使用的数据库。
from selenium import webdriver import sqlite3 def get_cookies(url): """ Returns the cookies from the response of `url` when making a HTTP GET request. """ co = webdriver.ChromeOptions() co.add_argument("--user-data-dir=chrome_dir") # creates a directory to store all the chrome data driver = webdriver.Chrome(chrome_options=co) driver.get(url) driver.quit() conn = sqlite3.connect(r'./chrome_stuff/Default/Cookies') c = conn.cursor() c.execute("SELECT * FROM 'cookies'") return c.fetchall()