Handling “Download” window by Firefox WebDriver

2019-04-02 04:01发布

问题:

I'm experimenting with Firefox's WebDriver and I'd like to ask if it is possible to handle "Download" window (to accept or decline incoming download request)?

For example, simple piece of code:

import selenium.firefox.webdriver

dr = selenium.firefox.webdriver.WebDriver()
# Firefox is showed up.

# Let's say I'd want to download python.
dr.get('http://python.org/ftp/python/3.1.3/python-3.1.3.msi')
# Download window is showed up.
# How could I accept the download request?

# As I understand, the method below should return 
# two handles but I get only main window's handle. 
handles = dr.get_window_handles()

# Seems like WebDriver cannot "see" this popup.

I've experimented with this a little bit but haven't found the solution yet. I'd really appreciate any hint.

Many thanks, - V

回答1:

One solution to this is changing WebDriver's Firefox profile to automatically download some MIME types to a given directory.

I'm not sure how (or if) this is exposed in Python, but it's mentioned on the Ruby bindings page on the Selenium wiki (under "Tweaking Firefox preferences").



回答2:

I don't think that this is the sort of thing that WebDriver was built for, but I'll take a crack at it. There is nothing built into the Firefox WebDriver to handle this specific case, but there are a few approaches you may take.

You can open FF with the profile that your WebDriver script uses and edit the preferences to always save the file instead of asking (Options > Applications > Windows Installer Package - set to "Save File"). Now, however, there's no way to tell that the file is downloading from the browser unless you get redirected to a 404 page. If not, you can check if the file exists in the Downloads directory for the same profile (Options > Main > Donwloads). If it's still in the process of downloading, the filename will be WhateverFileName.ext.part

Your other option is to use the non-visual HTMLUnit driver, navigate to the download link, click it, and the get the page source (will be the contents of the file). This works with textual files, I can't guarantee that it will work similarly for binaries, nor do I know how it will be encoded in such a case.

Best of luck



回答3:

i came across this when i was trying to download a file using capybara and got halted by the download prompt

SeleniumHQ : Selenium WebDriver

profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = "/Downloads"
profile['browser.download.folderList'] = 2
profile['browser.helperApps.neverAsk.saveToDisk'] = "audio/wav"
driver = Selenium::WebDriver.for :firefox, :profile => profile
driver.navigate.to('http://www.address.com/file.wav')

this just downloads the file into the directory specified, no prompt :)

the other option that i came across was

Determining file MIME types to autosave using Firefox & Watir-WebDriver

i have tried watir before and it proved very useful