Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file using HTTP in WebDriver

I am trying to use the WebDriver to navigate through a https site and download a file using WebDriver. When I did it like this, the file download dialog popped up.

WebDriver driver = new ChromeDriver();
driver.get("http://xxx/file1.txt");

I am wondering is there any way just call a method in WebDriver to download the file using regular https request without simulating the click?

Thanks in advance.

like image 434
zs2020 Avatar asked Sep 05 '12 19:09

zs2020


People also ask

Can we download file using Selenium?

On executing this script, the tester should be able to automate file download using Selenium and Python. After executing the script the file will be downloaded to the desired location. Now you can navigate to the folder mentioned in Step 2, and get the Selenium downloaded file.

How do you download any file and save it to the desired location using Selenium WebDriver?

New Selenium IDE We can download any file and save it to the desired location with Selenium. This can be done by creating an instance of the FirefoxOptions class. Then with the help of the addPreference method, we have to set the browser preferences.


2 Answers

There is not, at least not any way that works in all browsers. You might be able to configure some browsers (Firefox and Chrome) to download files to a specified location without prompting. However, for something like what you're asking about, you don't need Selenium at all. Any programmatic HTTP client will do. In Java, I'd recommend looking at HttpClient from Apache; in .NET using an HttpWebRequest will get the job done. Note that if the site you're downloading the file from requires authentication, you may need to specify custom headers in your HTTP request.

As a side note, you might want to reevaluate why you think you need to test downloading a file, if it's not as simple as executing an HTTP request outside the browser. This article discusses the issue in great detail, and provides a very well-reasoned argument why testing downloading a file is problematic, and often unnecessary.

like image 173
JimEvans Avatar answered Oct 11 '22 14:10

JimEvans


Yes you can. You need to setup a custom Chromedriver profile:

profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = download_directory

It will not prompt any dialogs. I had a more detailed answer on how to setup the download directory and validate that the file is of any given size here.

Additional chromedriver switches can be found here: http://peter.sh/experiments/chromium-command-line-switches/

like image 32
Sveatoslav Avatar answered Oct 11 '22 16:10

Sveatoslav