FireFox用户配置文件
Firefox 将用户个人信息(例如书签、密码、首选项、扩展、Cookie、证书等)保存在一系列文件中,它们被叫做用户配置文件,它们与 Firefox 的程序文件保存在不同位置。
因此,WebDriver如果能够加载已有的FireFox用户配置文件可带来很多便利!
查找用户配置文件
Firefox默认在本地路径C:\Users\<your Windows login username>\AppData\Roaming\Mozilla\Firefox\Profiles\
保存配置文件,可通过以下方式获取路径。
-
在运行框中输入
%APPDATA%\Mozilla\Firefox\Profiles\
并按下回车键。 -
在 Firefox 地址栏输入
about:profiles
并按下回车键。
-
在 Firefox 地址栏输入
about:support
并按下回车键。
加载FireFox用户配置文件
根据《Selenium3 Python WebDriver API源码探析(18)FireFox WebDriver实现,安装扩展》可知,webdriver在实例化时可设置firefox_profile
参数,取值为FirefoxProfile
对象或字符串。如果没有定义,将在操作系统的临时目录中生成一个新的自定义配置文件。
FirefoxProfile
对象为selenium\webdriver\firefox\firefox_profile.py
中FirefoxProfile
类的实例。
类签名为:class FirefoxProfile(profile_directory=None):
参数profile_directory
为用户配置文件路径。
案例:加载FireFox用户配置文件
import selenium.webdriver as webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
# 用户配置文件路径
profile_path = r'C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\1yh6m4pk.default-release'
# 创建FirefoxProfile对象
my_profile = FirefoxProfile(profile_directory=profile_path)
# 设置webdriver启动时加载的用户配置文件
driver = webdriver.Firefox(firefox_profile=my_profile)
print(driver.firefox_profile.path)
控制台输出:
C:\Users\Administrator\AppData\Local\Temp\1\tmppd69_1qi\webdriver-py-profilecopy
注意,用户配置文件比较大的慎重使用!! Webdriver启动之后都会把指定的Firefox配置文件路径复制到临时目录中。每次使用的临时目录不同,使用不慎可能导致磁盘空间不足。
FirefoxProfile
类源码:
self.tempfolder = tempfile.mkdtemp()
newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy")
界面对比
正常浏览器的界面,书签添加了腾讯首页,扩展安装了Video DownloadHelper。
不加载用户配置文件,即新用户配置文件的geckodriver界面。
加载用户配置文件,观察可发现webdriver加载了之前添加的书签和扩展。
参考文献
https://support.mozilla.org/zh-CN/kb/%E7%94%A8%E6%88%B7%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6