python - 让 Selenium 捕获所有的 cookies

标签 python cookies selenium

我被告知要对我们的前置网站进行 cookie 审核,现在我们拥有很多域,所以我真的不打算手动挖掘每个提取 cookie 的网站。我决定使用 Selenium 。这一直有效到我想要获取第三方 cookie 的地步。

目前(python)我可以做

driver.get_cookies()

对于从我的域设置的所有 cookie,但这不会给我任何 Google、Twitter、Vimeo 或其他第 3 方 cookie

我试过修改 firefox 驱动中的 cookie 权限,但没有用。任何人都知道我怎样才能得到 tehm

最佳答案

您的问题已在 StackOverflow 上得到解答 here

第 1 步:您需要从 here 下载并安装 Firefox 的“获取所有 XML 格式的 Cookie”扩展程序(不要忘记在安装扩展后重新启动 Firefox)。

第 2 步: 执行此 python 代码让 Selenium 的 FirefoxWebDriver 将所有 cookie 保存到一个 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

关于python - 让 Selenium 捕获所有的 cookies ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200134/

相关文章:

java - 对在 HttpClient 中创建 cookie 的不同方法感到困惑

django - 使用 Django 设置紧凑的隐私政策

java - selenium 3.3.1 中的 Actions 类已弃用,使用 contextClick 寻找解决方案

java - 如何用selenium获取文本同级标签?

python - Shell - 尝试输出日志文件的最后部分(时间戳是分隔符)

python - 从列表中的每个项目中提取整数和 unicode

Python 套接字 : binding to '' vs socket. gethostname()

python - 如何在随机选择函数中选择两个实例?

python - 通过 django admin 将 excel 数据导入模型

java - 为什么 setmaxage 不允许超过 ~5 分钟的时间