如何使用 selenium-python 自動從彈出對話方塊中下載檔案?
我們可以使用帶 Python 的 Selenium Webdriver 自動從彈出對話方塊中下載檔案。單擊下載連結後,將出現一個對話方塊供使用者選擇各種選項來儲存檔案。
我們必須以程式設計方式配置下載操作所在路徑,以便每次啟動 Firefox 瀏覽器後,Firefox 的個人資料都能夠在所需位置執行下載。
開啟 Firefox 的位址列,並輸入 about:config 並按 Enter。所有瀏覽器首選項都將使用 編輯 和 切換 按鈕提供。我們將使用 Firefox 選項類設定瀏覽器的下載首選項。
示例
from selenium import webdriver from selenium.webdriver.firefox.options import Options #object of Options class op = Options() #save file to path defined for recent download with value 2 op.set_preference("browser.download.folderList",2) #disable display Download Manager window with false value op.set_preference("browser.download.manager.showWhenStarting", False) #download location op.set_preference ("browser.download.dir","C:\Users\ghs6kor\Documents\Download") #MIME set to save file to disk without asking file type to used to open file op.set_preference ("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream,application/vnd.ms-excel") #set geckodriver.exe path driver = webdriver.Firefox(executable_path="C:\geckodriver.exe", firefox_options=op) driver.maximize_window() #launch URL driver.get("https://the-internet.herokuapp.com/download"); #click download link l = driver.find_element_by_link_text("xls-sample1.xls") l.click()
輸出
檔案已下載到宣告的位置。
廣告