让selenium获取所有cookie

4 投票
4 回答
5286 浏览
提问于 2025-04-17 20:56

我被要求对我们的网站进行一个“饼干审计”,也就是检查一下网站上使用的cookies。我们有很多域名,所以我可不想一个个手动去找这些cookies。我决定用selenium来帮忙。这个方法在我想获取第三方cookies的时候就遇到问题了。

现在(用python),我可以这样做:

driver.get_cookies()

这段代码可以获取我自己域名下设置的所有cookies,但却无法获取到Google、Twitter、Vimeo或者其他第三方的cookies。

我尝试过在firefox驱动中修改cookie的权限,但没有效果。有没有人知道我该怎么才能获取到这些第三方cookies呢?

4 个回答

-1

你可以从浏览器的sqlite数据库文件中获取任何cookie,这个文件在你的个人资料文件夹里。 我在这里添加了一个更详细的回答: Selenium 2 获取域上的所有cookie

0

是的,我觉得Selenium不允许你去操作其他域名的cookies,只能处理当前域名的。

如果你知道要操作的域名,那你可以先去那个域名,但我想这不太可能。

如果可以跨网站访问cookies,那就会有很大的安全隐患。

2

Selenium只能获取当前网站的 cookies:

getCookies

java.util.Set getCookies()

这个方法可以获取当前网站的所有 cookies。这就相当于在浏览器里输入 "document.cookie" 然后解析出来的结果。

不过,我听说有人用过一个 Firefox 插件,可以把所有的 cookies 保存为 XML 格式。就我所知,这可能是你最好的选择。

3

你的问题在StackOverflow上已经有答案了,点击这里可以查看。

第一步:你需要从这里下载并安装“Get All Cookies in XML”这个Firefox扩展(安装完扩展后,记得重启Firefox)。

第二步:运行下面的Python代码,这样Selenium的FirefoxWebDriver就能把所有的cookies保存到一个xml文件里,然后你可以读取这个文件:

from xml.dom import minidom
from selenium import webdriver
import os
import time


def determine_default_profile_dir():
    """
    Returns path of Firefox's default profile directory

    @return: directory_path
    """
    appdata_location = os.getenv('APPDATA')
    profiles_path = appdata_location + "/Mozilla/Firefox/Profiles/"
    dirs_files_list = os.listdir(profiles_path)
    default_profile_dir = ""
    for item_name in dirs_files_list:
        if item_name.endswith(".default"):
            default_profile_dir = profiles_path + item_name
    if not default_profile_dir:
        assert ("did not find Firefox default profile directory")

    return default_profile_dir


#load firefox with the default profile, so that the "Get All Cookies in XML" addon is enabled
default_firefox_profile = webdriver.FirefoxProfile(determine_default_profile_dir())
driver = webdriver.Firefox(default_firefox_profile)


#trigger Firefox to save value of all cookies into an xml file in Firefox profile directory
driver.get("chrome://getallcookies/content/getAllCookies.xul")
#wait for a bit to give Firefox time to write all the cookies to the file
time.sleep(40)

#cookies file will not be saved into directory with default profile, but into a temp directory.
current_profile_dir = driver.profile.profile_dir
cookie_file_path = current_profile_dir+"/cookie.xml"
print "Reading cookie data from cookie file: "+cookie_file_path

#load cookies file and do what you need with it
cookie_file = open(cookie_file_path,'r')
xmldoc = minidom.parse(cookie_file)

cookie_file.close()
driver.close()

#process all cookies in xmldoc object

撰写回答