天天看點

Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻

FireFox使用者配置檔案

Firefox 将使用者個人資訊(例如書簽、密碼、首選項、擴充、Cookie、證書等)儲存在一系列檔案中,它們被叫做使用者配置檔案,它們與 Firefox 的程式檔案儲存在不同位置。

是以,WebDriver如果能夠加載已有的FireFox使用者配置檔案可帶來很多便利!

查找使用者配置檔案

Firefox預設在本地路徑

C:\Users\<your Windows login username>\AppData\Roaming\Mozilla\Firefox\Profiles\

儲存配置檔案,可通過以下方式擷取路徑。

  • 在運作框中輸入

    %APPDATA%\Mozilla\Firefox\Profiles\

    并按下Enter鍵。
  • 在 Firefox 位址欄輸入

    about:profiles

    并按下Enter鍵。
    Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻
  • 在 Firefox 位址欄輸入

    about:support

    并按下Enter鍵。
Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻

加載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。

Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻

不加載使用者配置檔案,即新使用者配置檔案的geckodriver界面。

Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻

加載使用者配置檔案,觀察可發現webdriver加載了之前添加的書簽和擴充。

Selenium3 Python WebDriver API源碼探析(19)加載FireFox使用者配置檔案FireFox使用者配置檔案加載FireFox使用者配置檔案案例:加載FireFox使用者配置檔案參考文獻

參考文獻

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