如何使用selenium-python自动下载弹出对话框中的文件

21 投票
13 回答
40461 浏览
提问于 2025-04-18 14:02

我正在尝试使用selenium-python自动下载弹出对话框中的文件。

火狐浏览器的弹出窗口长这样:

在这里输入图片描述

我想模拟点击“确定”按钮。

我找到了一些答案,像是这个如何在Selenium 2 Python中处理弹出窗口,它还让我去看了一些文档https://selenium-python.readthedocs.org/en/latest/navigating.html?highlight=popup#popup-dialogs

我试过这个

    alert = driver.switch_to_alert()
    #alert.send_keys(Keys.RETURN) #No alert is present

还有这个

    alert = driver.switch_to_alert()
    alert.accept()  #no alert is present

如果我运行pprint.pprint(driver.window_handles),它只打印出一个唯一的标识符——这说明只有一个窗口存在。

所以如果没有警告框,并且只有一个窗口——我该如何下载这些文件呢?

13 个回答

2

你有两个选择:

1) 创建一个自定义的Firefox浏览器配置文件,设置好下载位置,这样Firefox就不会在下载时询问你确认了。我刚查了一下,发现有个博客讲解了怎么做

2) 使用Sikuli来自动点击下载对话框。博客讲解了如何使用Sikuli

附注 - 我没有看那些博客,但我相信它们会给你一些提示。

3

今天我花了一些时间来解决这个问题(又来了... 我在家里已经有了解决办法,但没法拿到它...),在这个过程中我发现了这个... 但是没有一个解决方案对我有帮助,所以我想分享一下我自己是怎么解决这个问题的。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

dl_path = "/tmp/"
profile = FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", false)
profile.set_preference("browser.download.dir", dl_path)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
                          "text/plain,text/x-csv,text/csv,application/vnd.ms-excel,application/csv,application/x-csv,text/csv,text/comma-separated-values,text/x-comma-separated-values,text/tab-separated-values,application/pdf")
6

根据Amey的回答1)以及当然还有Yi Zeng的博客(用ruby写的),引用了Selenium本身的内容,Selenium并不能直接和系统级的对话框互动,另外还有文档,下面是解决这个问题的Python代码片段。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

profile = FirefoxProfile()
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/pdf')
driver = webdriver.Firefox(firefox_profile=profile)

driver.get(target_url)
#specific to target_url
driver.find_element_by_css_selector('a[title="Click to Download"]').click()
7

我发现了一个很有用的解决办法,希望能帮助到某些人。

如果你在用火狐浏览器下载文件时,按住ALT键点击下载链接,就可以完全跳过提示。

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
...
profile.set_preference("browser.altClickSave", True)
...
element = driver.find_element_by_xpath("//a")
ActionChains(driver).key_down(Keys.ALT).click(element).key_up(Keys.ALT).perform()

这样下载任何文件时,都不需要指定文件的类型。

17

在Python中,这个方法也适用于Java,因为Firefox的设置是用JavaScript写的:

profile.set_preference("browser.download.panel.shown", False)
profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/vnd.ms-excel")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/vnd.ms-excel")
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.dir", "c:\\firefox_downloads\\")
browser = webdriver.WebDriver(firefox_profile=profile)

这个方法适用于CSV文件,如果你下载其他类型的文件,可以根据需要进行修改。

撰写回答