如何让Python调用的Firefox固定使用指定配置文件文件夹?
问题描述
使用Python调用Firefox浏览器实例时,每次启动都会自动新建配置文件文件夹,无法复用指定的d:\Python\WhatsApp配置文件夹。当前环境版本:Python 3.8.10、Selenium 3.141.0、Firefox WebDriver 0.34.0,运行系统为Windows 7 x64,原实现代码如下:
import os from selenium import webdriver def open_whatsapp(): # Specify the profile path profile_path = "d:\\Python\\WhatsApp" # Create browser options object options = webdriver.FirefoxOptions() # Set the profile path in the options options.set_preference("profile", profile_path) # Initialize the driver driver = webdriver.Firefox(options=options) # Open WhatsApp in the browser driver.get("https://web.whatsapp.com/") # Print the path to the current profile print("Current Firefox profile path:", profile_path) if __name__ == "__main__": open_whatsapp()
解决方案
问题原因
原代码中使用options.set_preference("profile", profile_path)的方式是错误的,Selenium 3.x版本中,这个设置无法让Firefox识别并加载指定的现有配置文件夹,因此浏览器会默认创建临时配置文件。
修改步骤
在Selenium 3.x中,正确指定Firefox现有配置文件夹的方式是使用FirefoxProfile类,具体修改如下:
- 导入
FirefoxProfile类 - 通过指定路径创建
FirefoxProfile实例 - 将该实例传入
webdriver.Firefox的firefox_profile参数
修改后的完整代码
import os from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile def open_whatsapp(): # 指定配置文件夹路径 profile_path = "d:\\Python\\WhatsApp" # 创建FirefoxProfile实例,加载指定路径的配置 firefox_profile = FirefoxProfile(profile_path) # 初始化驱动,传入profile参数 driver = webdriver.Firefox(firefox_profile=firefox_profile) # 打开WhatsApp网页版 driver.get("https://web.whatsapp.com/") # 打印当前使用的配置路径 print("Current Firefox profile path:", profile_path) if __name__ == "__main__": open_whatsapp()
额外说明
如果需要同时使用FirefoxOptions的其他设置,可以将firefox_profile和options参数同时传入webdriver.Firefox,例如:
driver = webdriver.Firefox(firefox_profile=firefox_profile, options=options)
内容的提问来源于stack exchange,提问作者Dmitriy P
相关产品推荐
相关产品推荐

