Selenium Python:如何在Firefox配置文件中保存并复用Cookies
问题根源
你当前的配置方式存在几处关键错误:
- 错误使用
set_preference('profile', ...)指定配置文件,Firefox无法正确识别并加载该配置,自然不会将会话Cookies写入对应文件。 - 手动调用
add_cookie是冗余操作——你是将当前会话已有的Cookies重复添加,且该方法仅作用于当前会话,不会写入本地配置文件的cookies.sqlite。 - 若未用
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
相关产品推荐
相关产品推荐

