首页 > 解决方案 > 如何克服 Firefox 提示保存文件

问题描述

一直试图让 python selenium 通过 Firefox 浏览器保存一个 excel 文件(.xlsx)。我的自动化程序因提示保存或打开 Firefox 正在访问的文件而中断。我尝试在线搜索解决方法和解决方案,但这些解决方案都没有奏效。我试过这个reddit线程,没有用,这个stackoverflow线程和这个其他stackoverflow线程也没有帮助。

我当前的代码是这样的:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Starting Firefox
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 1) # 0 means to download to the desktop, 1 means to download to the default "Downloads" directory, 2 means to use the directory
fp.set_preference("browser.helperApps.alwaysAsk.force", False)
mime_types = [
    'text/plain',
    'attachment/vnd.ms-excel',
    'text/csv',
    'application/csv',
    'text/comma-separated-values',
    'application/download',
    'application/octet-stream',
    'binary/octet-stream',
    'application/binary',
    'application/x-unknown',
    'application/excel',
    'attachment/csv',
    'attachment/excel'
]
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", ",".join(mime_types))
fp.set_preference("browser.preferences.instantApply",True)
fp.set_preference("browser.download.manager.showWhenStarting",False)
browser = webdriver.Firefox(firefox_profile=fp, firefox_binary=None, timeout=30, capabilities=None, proxy=None, executable_path='/Users/cadellteng/Downloads/geckodriver', options=None, firefox_options=None, service_args=None, desired_capabilities=None, log_path=None, keep_alive=True)
browser.get('https://sg.quickHR.co')

如果有人有一个工作代码向我展示或告诉我我在这里做错了什么,我将非常感激。提前致谢。

标签: pythonseleniumfirefox

解决方案


问题在于 MIME 类型。您可以在Network选项卡 - Response Headers 中获取 mime 类型content-type

尝试以下:

mime_types = [
    'text/plain',
    'attachment/vnd.ms-excel',
    'text/csv',
    'application/csv',
    'text/comma-separated-values',
    'application/download',
    'application/octet-stream',
    'binary/octet-stream',
    'application/binary',
    'application/x-unknown',
    'application/excel',
    'attachment/csv',
    'attachment/excel'
    'application/vnd.ms-excel',
    'application/msexcel',
    'application/x-msexcel',
    'application/x-ms-excel',
    'application/x-excel',
    'application/x-dos_ms_excel',
    'application/xls',
    'application/x-xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]

推荐阅读