How to see all cookies being set when a GET request is made
引用未使用python请求模块获取所有cookie信息
OP在chrome上看到了很多cookie,但是在他的python请求代码中没有看到大多数cookie。给出的原因是"正在设置的cookie来自其他页面/资源,可能由javascript代码加载。"
这是我用来尝试获取访问URL时加载的cookie的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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。有了这个设置,我如何查看其他cookie,就像chrome看到它们一样?也就是说,在发出GET请求时,我如何看到所有正在设置的cookie,包括来自其他页面/资源的cookie?
做了点工作,但我设法使它工作起来。基本上需要硒和铬来实际加载网站和所有第三方的东西。其中一个输出是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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() |