You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Python:如何在Firefox配置文件中保存并复用Cookies

解决Selenium Firefox会话Cookies无法保存到配置文件的问题

问题根源

你当前的配置方式存在几处关键错误:

  1. 错误使用set_preference('profile', ...)指定配置文件,Firefox无法正确识别并加载该配置,自然不会将会话Cookies写入对应文件。
  2. 手动调用add_cookie是冗余操作——你是将当前会话已有的Cookies重复添加,且该方法仅作用于当前会话,不会写入本地配置文件的cookies.sqlite。
  3. 若未用driver.quit()正常关闭驱动,Firefox进程可能异常终止,导致Cookies未完成写入。

正确实现步骤

1. 正确加载指定Firefox配置文件

需通过FirefoxProfile对象指定配置文件路径,再传入Options中,确保Selenium使用你指定的配置会话:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

# 替换为你的实际配置文件路径
profile_path = '/Users/<username>/Library/Application Support/Firefox/Profiles/<new_profile>'
# 创建配置文件对象
firefox_profile = FirefoxProfile(profile_path)

ffOptions = Options()
ffOptions.headless = False
# 将配置文件绑定到Options
ffOptions.profile = firefox_profile

# 初始化驱动
driver = webdriver.Firefox(options=ffOptions)

2. 执行操作后正常关闭驱动

完成登录、搜索、浏览等操作后,必须调用driver.quit()而非driver.close()——quit()会触发Firefox正常退出,自动将会话Cookies写入配置文件的cookies.sqlite:

# 执行你的业务操作
driver.get("https://www.youtube.com")
# ... 登录、搜索、观看视频等操作 ...

# 正常关闭驱动,触发Cookies保存
driver.quit()

额外注意事项

  • 确保配置文件路径正确:替换<username>和<new_profile>为实际的系统用户名和Firefox配置文件夹名(可在Firefox的about:profiles页面查看路径)。
  • 避免冲突:不要在手动打开Firefox并使用该配置文件的同时,用Selenium启动驱动,否则配置文件会被锁定,无法写入Cookies。
  • 权限检查:确保当前用户对配置文件夹有读写权限,否则Firefox无法写入cookies.sqlite。

内容的提问来源于stack exchange,提问作者Kusanagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:41:19