如何在 Selenium Python 中将 cookie 保存到我的 Firefox 配置文件中并在下一个会话中再次加载它们?

问题描述 投票:0回答:1

我一直在使用 Selenium 登录 Firefox 上的一系列网页并搜索某些关键字。然后我访问 Youtube,观看视频,几秒钟后关闭驱动程序。由于 Firefox 配置文件中保留了 cookie,我希望能够观察推荐视频随时间的变化,但是似乎我的 cookie 没有被存储,到目前为止我已经尝试了以下(以及许多其他方法)启动驱动程序:

    ffOptions = Options()
    ffOptions.headless = False
#     ffOptions.add_argument('/Users/<username>/Library/Application Support/Firefox/Profiles/<new_profile>')
    ffOptions.set_preference('profile', '/Users/<username>/Library/Application Support/Firefox/Profiles/<new_profile>')

    driver = webdriver.Firefox(options = ffOptions)
    
    driver.get(url)

然后添加了这个来尝试将 cookie 保存到我的 Firefox 配置文件中:

    current_cookies = driver.get_cookies()
    for cookie in current_cookies:
        print(cookie)
        driver.add_cookie(cookie)

但这不会将 cookie 保存到我的个人资料中的 cookies.sqlite 中。有没有办法保存这些 cookie,以便我可以在下一次会话中再次加载它们?

python selenium firefox cookies
1个回答
0
投票

也许这会对您有所帮助: 我通常使用参数初始化用户数据路径中的网络驱动程序。 这将打开包含所有用户配置的浏览器,因此在重新打开驱动程序时可能会保留您的登录信息和 cookie。 在这种情况下,我使用的是 Edge,但我认为您可以使用其他浏览器,只需找到其用户数据文件夹所在的位置即可。

# Set home and userdata path
from pathlib import Path
home = str(Path.home())
userdata = Path(f'{home}\\AppData\\Local\\Microsoft\\Edge\\User Data')

# add option to the driver
from selenium.webdriver.edge.options import Options as EdgeOptions
opt = EdgeOptions()
opt.add_argument(f'--user-data-dir={userdata}')
© www.soinside.com 2019 - 2024. All rights reserved.