Python+Selenium实现Firefox文件自动下载:弹窗问题求助
解决Firefox+Selenium下载文件时弹出保存/打开弹窗的问题
我来帮你搞定这个烦人的弹窗问题!你的核心问题出在MIME类型配置错误,还有几个Firefox的关键下载偏好没设置到位,咱们一步步修正:
问题分析
先看你代码里的问题点:
application/text不是标准MIME类型,文本文件正确的类型是text/plaintxt/csv/xls这种格式完全错误,每种文件类型要对应专属的MIME类型,比如CSV是text/csv,Excel文件是application/vnd.ms-excel(旧版xls)或application/vnd.openxmlformats-officedocument.spreadsheetml.sheet(新版xlsx)- 两个
neverAsk配置里的逗号分隔有语法问题(比如第二个配置里少了逗号) - 缺少Firefox 60需要的额外下载管理器禁用配置
修正后的完整代码
from selenium import webdriver import time # 初始化Firefox配置文件 profile = webdriver.FirefoxProfile() # 设置下载路径为自定义文件夹(注意tempDir需要你提前定义好) profile.set_preference("browser.download.folderList", 2) # 2代表使用自定义路径 profile.set_preference("browser.download.dir", tempDir) # 彻底禁用下载管理器的弹窗和提示 profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.manager.useWindow", False) profile.set_preference("browser.download.manager.focusWhenStarting", False) profile.set_preference("browser.download.manager.closeWhenDone", True) # 配置自动保存的MIME类型,覆盖你需要的文件类型 auto_save_mimes = [ "text/plain", "application/pdf", "text/csv", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ] profile.set_preference("browser.helperApps.neverAsk.saveToDisk", ",".join(auto_save_mimes)) profile.set_preference("browser.helperApps.neverAsk.openFile", ",".join(auto_save_mimes)) # 针对PDF文件,禁用内置预览插件(避免触发预览弹窗) profile.set_preference("plugin.disable_full_page_plugin_for_types", "application/pdf") profile.set_preference("pdfjs.disabled", True) # 启动浏览器并执行下载操作 url = "http://www.seleniumeasy.com/test/generate-file-to-download-demo.html" driver = webdriver.Firefox(executable_path=firefox_path, firefox_profile=profile) driver.get(url) inpbox = driver.find_element_by_id("textbox") inpbox.send_keys("Lorem Ipsum \r\n") driver.find_element_by_id("create").click() time.sleep(2) driver.find_element_by_id("link-to-download").click()
关键配置说明
browser.download.folderList = 2:指定使用自定义下载路径,而非浏览器默认的下载文件夹browser.helperApps.neverAsk.saveToDisk:告诉Firefox这些MIME类型的文件直接保存,无需询问- 几个
browser.download.manager相关配置:彻底关闭下载管理器的弹窗、窗口聚焦等行为 - PDF相关配置:禁用Firefox内置的PDF预览插件,避免PDF文件触发预览弹窗而非直接下载
这样修改后,点击下载链接就会自动把文件保存到你指定的tempDir文件夹,不会再弹出询问窗口了。
内容的提问来源于stack exchange,提问作者abhi1610
相关产品推荐
相关产品推荐

