Testing File Download Functionality

How to test your web app’s File Download functionality on BrowserStack Automate

Introduction

You can test your web app’s File Download functionality in an Automate session. This guide shows you how to:

  • Download files on remote desktop instances.
  • Verify that the file downloaded successfully.
  • Check the downloaded files’ properties.
  • Transfer the downloaded file from BrowserStack desktop to your machine.

Supported Browsers and Operating Systems

Component List
Supported OS All desktop platforms
Supported Browsers Chrome, Safari, Firefox

Download files on remote desktop instances

The samples below show how to use Selenium to download a file on remote desktop instance in your Automate session:

import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;

public class JavaSample {

  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.folderList", 0);
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("browser.download.manager.focusWhenStarting", false);
    profile.setPreference("browser.download.useDownloadDir", true);
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.closeWhenDone", true);
    profile.setPreference("browser.download.manager.showAlertOnComplete", false);
    profile.setPreference("browser.download.manager.useWindow", false);
    /* you will need to find the content-type of your app and set it here. */
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Firefox");
    caps.setCapability("browser_version", "67.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("os_version", "10");
    caps.setCapability("name", "Bstack-[Java] Sample Test");
    caps.setCapability(FirefoxDriver.PROFILE, profile);

    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
    driver.get("https://rubygems.org/gems/selenium-webdriver");
    WebElement element = driver.findElement(By.id("download"));
    element.click();

    Thread.sleep(50000);
    driver.quit();
  }
}
var webdriver = require('selenium-webdriver');

// Initialize Firefox profile to set download preferences
var firefox = require('selenium-webdriver/firefox');
var profile = new firefox.Profile();

profile.setPreference('browser.download.folderList', 0);
profile.setPreference('browser.download.manager.showWhenStarting', false);
profile.setPreference('browser.download.manager.focusWhenStarting', false);
profile.setPreference('browser.download.useDownloadDir', true);
profile.setPreference('browser.helperApps.alwaysAsk.force', false);
profile.setPreference('browser.download.manager.alertOnEXEOpen', false);
profile.setPreference('browser.download.manager.closeWhenDone', true);
profile.setPreference('browser.download.manager.showAlertOnComplete', false);
profile.setPreference('browser.download.manager.useWindow', false);
profile.setPreference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream');

// Input capabilities
var capabilities = {
 'browserName' : 'Firefox',
 'browser_version' : '67.0',
 'os' : 'Windows',
 'os_version' : '10',
 'browserstack.user' : 'YOUR_USERNAME',
 'browserstack.key' : 'YOUR_ACCESS_KEY',
 'name' : 'Bstack-[Node] Sample Test',
 'firefox_profile' : profile
}

var driver = new webdriver.Builder().
  usingServer('http://hub-cloud.browserstack.com/wd/hub').
  withCapabilities(capabilities).
  build();

driver.get('https://rubygems.org/gems/selenium-webdriver').then(function(){
  driver.findElement(webdriver.By.id('download')).click().then(function(){
    setTimeout(function() {
       driver.quit();
    }, 55000);
  });
});
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumTest {
  class Program {
    static void Main(string[] args) {
      IWebDriver driver;

      FirefoxProfile firefoxProfile = new FirefoxProfile();            
      firefoxProfile.SetPreference("browser.download.folderList", 0);
      firefoxProfile.SetPreference("browser.download.manager.focusWhenStarting", false);
      firefoxProfile.SetPreference("browser.download.useDownloadDir", true);
      firefoxProfile.SetPreference("browser.helperApps.alwaysAsk.force", false);
      firefoxProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
      firefoxProfile.SetPreference("browser.download.manager.closeWhenDone", true);
      firefoxProfile.SetPreference("browser.download.manager.showAlertOnComplete", false);
      firefoxProfile.SetPreference("browser.download.manager.useWindow", false);
      firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/force-download");

      DesiredCapabilities capability = new DesiredCapabilities();
      capability.SetCapability("browser", "Firefox");
      capability.SetCapability("browser_version", "67.0");
      capability.SetCapability("os", "Windows");
      capability.SetCapability("os_version", "10");
      capability.SetCapability("browserstack.user", "YOUR_USERNAME");
      capability.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
      capability.SetCapability("name", "Bstack-[C_sharp] Sample Test");
      capability.SetCapability(FirefoxDriver.ProfileCapabilityName, firefoxProfile.ToBase64String());

      driver = new RemoteWebDriver(
        new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
      );
      driver.Navigate().GoToUrl("https://rubygems.org/gems/selenium-webdriver");
      driver.FindElement(By.Id("download")).Click();
      driver.Quit();
    }
  }
}
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 0)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.manager.focusWhenStarting', False)
profile.set_preference('browser.download.useDownloadDir', True)
profile.set_preference('browser.helperApps.alwaysAsk.force', False)
profile.set_preference('browser.download.manager.alertOnEXEOpen', False)
profile.set_preference('browser.download.manager.closeWhenDone', True)
profile.set_preference('browser.download.manager.showAlertOnComplete', False)
profile.set_preference('browser.download.manager.useWindow', False)
# you will need to find the content-type of your app and set it here. We are downloading a gzip file.
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/x-gzip')
profile.update_preferences()

desired_cap = {
 'browser': 'Firefox',
 'browser_version': '67.0',
 'os': 'Windows',
 'os_version': '10',
 'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities=desired_cap, browser_profile=profile)

driver.get("http://pypi.python.org/pypi/selenium")
driver.find_element_by_partial_link_text("selenium-2").click()
driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.folderList'] = 0
profile['browser.download.manager.showWhenStarting'] = false
profile['browser.download.manager.focusWhenStarting'] = false
profile['browser.download.useDownloadDir'] = true
profile['browser.helperApps.alwaysAsk.force'] = false
profile['browser.download.manager.alertOnEXEOpen'] = false
profile['browser.download.manager.closeWhenDone'] = true
profile['browser.download.manager.showAlertOnComplete'] = false
profile['browser.download.manager.useWindow'] = false
# you will need to find the content-type of your app and set it here.
profile['browser.helperApps.neverAsk.saveToDisk'] = "application/octet-stream"

caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)
caps['browser'] = 'Firefox'
caps['browser_version'] = '67.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = 'Bstack-[Ruby] Sample Test'


driver = Selenium::WebDriver.for(:remote,
  :url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
  :desired_capabilities => caps)
driver.navigate.to "https://rubygems.org/gems/selenium-webdriver"
driver.find_element(:id => 'download').click
driver.quit
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.net.URL;

public class FileDownload {

    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

    public static void main(String[] args) throws Exception {

        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("os", "Windows");
        caps.setCapability("os_version", "10");
        caps.setCapability("browser", "Chrome");
        caps.setCapability("browser_version", "75.0");
        caps.setCapability("name", "Bstack-[Java] Sample Test");

        WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices");
        Thread.sleep(2000);

        //Find element by link text and store in variable "Element"
        WebElement Element = driver.findElement(By.className("icon-csv"));

        //This will scroll the page till the element is found
        jse.executeScript("arguments[0].scrollIntoView();", Element);
        jse.executeScript("window.scrollBy(0,-100)");
        Thread.sleep(1000);

        //Click on the element to download the file
        Element.click();
        Thread.sleep(2000);

        driver.quit();
    }
}
const {Builder, By, Key, until} = require('selenium-webdriver');
const fs = require("fs");

// Input capabilities
let capabilities = {
    'browserName' : 'Chrome',
    'browser_version' : '75.0',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY',
    'name': 'Bstack-[Node] Sample Test'
}

async function main() {
    let driver = await new Builder()
        .usingServer('http://hub-cloud.browserstack.com/wd/hub')
        .withCapabilities(capabilities)
        .build();

    await driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices')

    const element = await driver.findElement(By.className('icon-csv'))
    await driver.executeScript('arguments[0].scrollIntoView();', element)
    await driver.executeScript('window.scrollBy(0,-200)')
    await element.click()

    await driver.quit()
}
main()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Threading;

namespace SeleniumTest {
    class FileDownload {
        static void Main(string[] args) {
            IWebDriver driver;
            DesiredCapabilities capability = new DesiredCapabilities();
            capability.SetCapability("browser", "Chrome");
            capability.SetCapability("browser_version", "75.0");
            capability.SetCapability("os", "Windows");
            capability.SetCapability("os_version", "10");
            capability.SetCapability("browserstack.user", "YOUR_USERNAME");
            capability.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
            capability.SetCapability("name", "Bstack-[C_sharp] Sample Test");

            driver = new RemoteWebDriver(
                new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
            );
            IJavaScriptExecutor jse = (IJavaScriptExecutor) driver;

            driver.Navigate().GoToUrl("https://www.browserstack.com/test-on-the-right-mobile-devices");
            Thread.Sleep(2000);

            //Find element by link text and store in variable "Element"             
            IWebElement Element = driver.FindElement(By.ClassName("icon-csv"));

            //This will scroll the page till the element is found       
            jse.ExecuteScript("arguments[0].scrollIntoView();", Element);
            jse.ExecuteScript("window.scrollBy(0,-100)");
            Thread.Sleep(2000);

            Element.Click();
            Thread.Sleep(2000);

            driver.Quit();
        }
    }
}
from selenium
import webdriver
import time
import base64

desired_cap = {
    'browser': 'Chrome',
    'browser_version': '75.0',
    'os': 'Windows',
    'os_version': '10',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor = 'http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities = desired_cap)

driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices")
time.sleep(2)

# Accept the cookie popup
driver.find_element_by_link_text("Got it").click()
time.sleep(2)

# Find element by class name and store in variable "Element"
element = driver.find_element_by_class_name("icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
time.sleep(2)

# Click on the element to download the file
element.click()
time.sleep(2)

driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'Chrome'
caps['browser_version'] = '75.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = '[Bstack-[Ruby] Sample Test'

driver = Selenium::WebDriver.for(: remote,: url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",: desired_capabilities => caps)
driver.navigate.to "https://www.browserstack.com/test-on-the-right-mobile-devices"
sleep(2)

# Accept the cookie popup
driver.find_element(: link_text, "Got it").click

# Find element by class name and store in variable "Element"
element = driver.find_element(: class_name, "icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
sleep(2)

# Click on the element to download the file
element.click
sleep(2)

# Execute this action to click "Save File" button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
sleep(2)

driver.quit
if driver
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.net.URL;

public class FileDownload {

    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

    public static void main(String[] args) throws Exception {

        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("os", "Windows");
        caps.setCapability("os_version", "10");
        caps.SetCapability("browser", "IE");
        caps.SetCapability("browser_version", "11.0");
        caps.setCapability("name", "Bstack-[Java] Sample Test");

        WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices");
        Thread.sleep(2000);
        //Find element by link text and store in variable "Element"
        WebElement Element = driver.findElement(By.className("icon-csv"));

        //This will scroll the page till the element is found
        jse.executeScript("arguments[0].scrollIntoView();", Element);
        jse.executeScript("window.scrollBy(0,-100)");
        Thread.sleep(1000);

        //Click on the element to download the file
        Element.click();
        Thread.sleep(2000);

        driver.quit();
    }
}
const {Builder, By, Key, until} = require('selenium-webdriver');
const fs = require("fs");

// Input capabilities
let capabilities = {
    'browserName' : 'IE',
    'browser_version' : '11.0',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY',
    'name': 'Bstack-[Node] Sample Test'
}

async function main() {
    let driver = await new Builder()
        .usingServer('http://hub-cloud.browserstack.com/wd/hub')
        .withCapabilities(capabilities)
        .build();

    await driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices')

    const element = await driver.findElement(By.className('icon-csv'))
    await driver.executeScript('arguments[0].scrollIntoView();', element)
    await driver.executeScript('window.scrollBy(0,-200)')
    await element.click()

    // Execute this action to click "Save File" button in the browser prompt
    await driver.executeScript('browserstack_executor: {"action": "saveFile"}')

    await driver.quit()
}
main()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Threading;

namespace SeleniumTest {
    class FileDownload {
        static void Main(string[] args) {
            IWebDriver driver;
            DesiredCapabilities capability = new DesiredCapabilities();
            capability.SetCapability("browser", "IE");
            capability.SetCapability("browser_version", "11.0");
            capability.SetCapability("os", "Windows");
            capability.SetCapability("os_version", "10");
            capability.SetCapability("browserstack.user", "YOUR_USERNAME");
            capability.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
            capability.SetCapability("name", "Bstack-[C_sharp] Sample Test");

            driver = new RemoteWebDriver(
                new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
            );
            IJavaScriptExecutor jse = (IJavaScriptExecutor) driver;

            driver.Navigate().GoToUrl("https://www.browserstack.com/test-on-the-right-mobile-devices");
            Thread.Sleep(2000);

            //Find element by link text and store in variable "Element"             
            IWebElement Element = driver.FindElement(By.ClassName("icon-csv"));

            //This will scroll the page till the element is found       
            jse.ExecuteScript("arguments[0].scrollIntoView();", Element);
            jse.ExecuteScript("window.scrollBy(0,-100)");
            Thread.Sleep(2000);

            Element.Click();
            Thread.Sleep(2000);

            jse.ExecuteScript("browserstack_executor: {\"action\": \"saveFile\"}");
            Thread.Sleep(2000);

            driver.Quit();
        }
    }
}
from selenium
import webdriver
import time
import base64

desired_cap = {
    'browser': 'IE',
    'browser_version': '11.0',
    'os': 'Windows',
    'os_version': '10',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor = 'http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities = desired_cap)

driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices")
time.sleep(2)

# Accept the cookie popup
driver.find_element_by_link_text("Got it").click()
time.sleep(2)

# Find element by class name and store in variable "Element"
element = driver.find_element_by_class_name("icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
time.sleep(2)

# Click on the element to download the file
element.click()
time.sleep(2)

# Execute this action to click "Save File" button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
time.sleep(2)

driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'IE'
caps['browser_version'] = '11.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['nativeEvents'] = 'true'
caps['name'] = 'Bstack-[Ruby] Sample Test'

driver = Selenium::WebDriver.for(: remote,: url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",: desired_capabilities => caps)
driver.navigate.to "https://www.browserstack.com/test-on-the-right-mobile-devices"
sleep(2)

# Accept the cookie popup
driver.find_element(: link_text, "Got it").click

# Find element by class name and store in variable "Element"
element = driver.find_element(: class_name, "icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
sleep(2)

# Click on the element to download the file
element.click
sleep(2)

# Execute this action to click "Save File" button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
sleep(2)

driver.quit
if driver

Verify that the file downloaded successfully

BrowserStack has a custom browserstack_executor script. You can use this to check whether the file downloaded successfully in an Automate session.

The fileExists function will return a boolean value as a response.

Verify that a specific file was downloaded

You can verify whether a specific file was downloaded. The following snippet shows you how:

System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"<file name>\"}}"));
driver.executeScript('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "<file name>"}}')
Driver.ExecuteJavaScript('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "<file name>"}}');
driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "<file name>"}}')"
driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "<file name>"}}')

Verify that the last file download completed successfully

The following snippet verifies whether a file was downloaded in the test session.

System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"fileExists\"}"));
driver.executeScript('browserstack_executor: {"action": "fileExists"}')
Driver.ExecuteJavaScript('browserstack_executor: {"action": "fileExists"}');
driver.execute_script('browserstack_executor: {"action": "fileExists"}')"
driver.execute_script('browserstack_executor: {"action": "fileExists"}')

Check the downloaded files’ properties

To verify the integrity of the downloaded file, use the getFileProperties function. This returns the file properties hash.

System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"<file name>\"}}"));
driver.executeScript('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "<file name>"}}')
Driver.ExecuteJavaScript('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "<file name>"}}');
driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "<file name>"}}')"
driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "<file name>"}}')

Transfer the downloaded file from BrowserStack desktop to your machine

The getFileContent function returns the downloaded file as a Base64-encoded string.

System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"<file name>\"}}"));
driver.executeScript('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "<file name>"}}')
Driver.ExecuteJavaScript('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "<file name>"}}');
driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "<file name>"}}')"
driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "<file name>"}}')

Code Sample

import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;

public class FileDownload {

  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.folderList", 0);
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("browser.download.manager.focusWhenStarting", false);
    profile.setPreference("browser.download.useDownloadDir", true);
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.closeWhenDone", true);
    profile.setPreference("browser.download.manager.showAlertOnComplete", false);
    profile.setPreference("browser.download.manager.useWindow", false);
    /*You will need to find the content-type of your app and set it here. */
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Firefox");
    caps.setCapability("browser_version", "67.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("os_version", "10");
    caps.setCapability("name", "Bstack-[Java] Sample Test");
    caps.setCapability(FirefoxDriver.PROFILE, profile);

    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
    driver.get("https://rubygems.org/gems/selenium-webdriver");

    JavascriptExecutor jse = (JavascriptExecutor) driver;
    WebElement element = driver.findElement(By.id("download"));
    element.click();

    Thread.sleep(50000);
    driver.quit();
  }
}
const {
  Builder,
  By,
  Key,
  until
} = require('selenium-webdriver');
const fs = require("fs");
const webdriver = require('selenium-webdriver');
const bb = require('bluebird');
var sleep = require('sleep');
var FirefoxProfile = require('firefox-profile');
var profile = new FirefoxProfile();

profile.setPreference('browser.download.folderList', 0);
profile.setPreference('browser.download.manager.showWhenStarting', false);
profile.setPreference('browser.download.manager.focusWhenStarting', false);
profile.setPreference('browser.download.useDownloadDir', true);
profile.setPreference('browser.helperApps.alwaysAsk.force', false);
profile.setPreference('browser.download.manager.alertOnEXEOpen', false);
profile.setPreference('browser.download.manager.closeWhenDone', true);
profile.setPreference('browser.download.manager.showAlertOnComplete', false);
profile.setPreference('browser.download.manager.useWindow', false);
//You will need the content-type of your app from developer tools on your browser and set it here. We are downloading a csv file.
profile.setPreference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream');
profile.updatePreferences();
profile.encode((err, encoded) => {

  let capabilities = {
    'browserName': 'firefox',
    'browser_version': '67.0',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY',
    'name': 'file download test',
    'build': 'Download files',
    'firefox_profile': encoded
  }

  var driver = new webdriver.Builder().
  usingServer('http://hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();

  //Navigate to the link
  driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices').then(function() {

    //Find element by class name and store in variable "element"             
    driver.findElement(By.className('icon-csv')).then(function(element) {

      //This will scroll the page till the element is found   
      driver.executeScript('arguments[0].scrollIntoView();', element).then(function() {
        driver.executeScript('window.scrollBy(0,-200)').then(function() {

          //Accept the cookie popup
          driver.findElement(By.id("accept-cookie-notification")).click().then(function() {

            //Click on the element to download the file
            element.click().then(function() {
              bb.delay(5000).then(function() {
                driver.quit();
              });
            });
          });
        });
      });
    });
  });
});
using System.Collections.Generic;
using System.Threading;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium;
using System.IO;

namespace downloading_files {
  class MainClass {
    public static void Main(string[] args) {

      FirefoxProfile firefoxProfile = new FirefoxProfile();
      firefoxProfile.SetPreference("browser.download.showWhenStarting", false);
      firefoxProfile.SetPreference("browser.download.folderList", 0);
      firefoxProfile.SetPreference("browser.download.manager.focusWhenStarting", false);
      firefoxProfile.SetPreference("browser.download.useDownloadDir", true);
      firefoxProfile.SetPreference("browser.helperApps.alwaysAsk.force", false);
      firefoxProfile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
      firefoxProfile.SetPreference("browser.download.manager.closeWhenDone", true);
      firefoxProfile.SetPreference("browser.download.manager.showAlertOnComplete", false);
      firefoxProfile.SetPreference("browser.download.manager.useWindow", false);
      firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/force-download");

      DesiredCapabilities caps = new DesiredCapabilities();
      caps.SetCapability("os", "windows");
      caps.SetCapability("os_version", "10");
      caps.SetCapability("build", "Download Files on Firefox");
      caps.SetCapability("browser", "firefox");
      caps.SetCapability("browser_version", "67");
      caps.SetCapability("browserstack.user", "YOUR_USERNAME");
      caps.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
      caps.SetCapability("firefox_profile", firefoxProfile.ToBase64String());
      Dictionary < string, object > ffOpts = new Dictionary < string, object > ();

      //Encoded profile is added
      ffOpts.Add("profile", "UEsDBBQAAAAIAFydlE9vNRdlIQQAAOkOAAAHAAAAdXNlci5qc5VXTW/jNhC991cUPrVAzSa73Ut7cmMXKBA0xbrB9kZQ1MhiTJEsh7Tif9+haK+dtb5yEyUOOR/vvRlFBM+dh+qHRSmC8OCsD8rsmLNaySNLL7exaBSisubv7uVKSnABysVP31dCI/z423fxckzhbUsrVtrWaCtK1ggjdvSisjLilxrMlu5Jd/Tbl7Yhk1cua28b4Ci9coH7aHhQDZDNx7u3Bi0UpVcHWoMRhQZuRKAlhwOYgGQQfOy5I4fKhdb8BTm8ppgoxH6Dc1C2qrQy0O/5iziI7C6z+SyGtW3/NA/0aDX0ngyvAQx2m6OjbAPLUczNLn1bn57Xyo86X4N24FfOIRO6FUdc4Z6q4uVAPMK5WT4Fa/VeBRZAQwPBHym3LyAzQobdQRBe1qcbxqNFUUH3nJDZJOf9hE+nQi1FjlbblhdHXkIlog79mHgD/xqEDnVek6f+oCSwSnkMn6Ppv/KCQ4EYCbrR0C1IaeDEngjjxcFEiuhYTaB3xBdu6SSvSmANBttBbqF2xnpYjB+QjGnzXf+uIApklD7zZB60xYm8b54fV+zsyKj7V+c+ORjI0KXynZpQXFRGD12yKmI7l15g3W97yxNjg6qOz9gltscCQUavwpFJdCewzORUZXUJ/lFhuE3klR+FtnKvaddcyjasVYZuYWVs3JXRqCrIGuT+wTaOVK1QOgVk1K4O+jiR5G8AlQAkChvDr4UWZj+AIk2Z9SS24yGdNXpanG9g3YKWSdej1+MelXBIwoKM/CGNyhI6mrSvBa+UBnpi1qudMjy3suTcfN+YKEuVNFxMuHkWPwOhtX5/bnalwhPgbv08bWV1CETXWmF9XKbPjnRjqcHsQuLAh0+fBtvLWBYcEckFTIzkjS2FnijlsOxpu9ull6fcb+aA/I1Sj1786hQpAEkzQ9I1ESIJAYnBf1H5yUuok+lMjHVW9N/zl2G0nurBLYkTLwkcZscT1+d2tHc2wFyEbv+HmeNRGhWmp6Ov5gqdFkcoN/d3279ICbsm/kv/ZgMtoSFBfJ5SXQ0KhqYon+YEFAf4x64V7js+OEecEokgP1vq9GGJwYNoFhOMpF1KBv4tMUd8oVPLFC+EbqL4I7XgFSVIDpBrNL8rDT5Q56PiaBgaOs70zIbL8yRBWA0R302i6JIXo9y5mrNEDHagm6XmbygdDTQF+G23HHDnqnukA9cZ+1tJ4E8W9wOzwU3KZJoQEibXeQAZzjZlaM86bhHWcpN7B/Rpz5ezzQgUMozZZOd4M718ZOLyu3IbwEWF2loRf1M3HxehqzGvO/hqzJOErvH/h5vQRUbk5t/N8Ng048dsljZfipQA4nNrG6gRgq4wugzhnPBFP02kcOl3a5m2Cr08z8qzhIZelU8m1x7v75iiVNrnz48Tk8H0pH57+/9QSwECFAMUAAAACABcnZRPbzUXZSEEAADpDgAABwAAAAAAAAAAAAAApIEAAAAAdXNlci5qc1BLBQYAAAAAAQABADUAAABGBAAAAAA=");
      caps.SetCapability("moz:firefoxOptions", ffOpts);
      Console.WriteLine(caps.ToString());
      RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://hub-cloud.browserstack.com/wd/hub"), caps);

      //Navigate to the link
      driver.Navigate().GoToUrl("https://www.browserstack.com/test-on-the-right-mobile-devices");
      IJavaScriptExecutor jse = (IJavaScriptExecutor) driver;

      Thread.Sleep(2000);

      //This will scroll the page till the element is found
      driver.ExecuteScript("arguments[0].scrollIntoView();", driver.FindElementByClassName("icon-csv"));
      driver.ExecuteScript("window.scrollBy(0,-100)");
      Thread.Sleep(2000);

      //Find element by class name and then click"             
      driver.FindElementByClassName("icon-csv").Click();
      Thread.Sleep(5000);

      //Check if file exists
      bool val1 = (bool) driver.ExecuteScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
      Thread.Sleep(5000);
      Console.WriteLine(val1);

      //Get file properties
      Console.WriteLine(jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

      //Download the file locally
      jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
      string base64encode = (string) jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
      byte[] b = Convert.FromBase64String(base64encode);
      File.WriteAllBytes(@ "BrowserStack - List of devices to test on.csv", b);
      Thread.Sleep(2000);

      driver.Quit();
    }
  }
}
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 0)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.manager.focusWhenStarting', False)
profile.set_preference('browser.download.useDownloadDir', True)
profile.set_preference('browser.helperApps.alwaysAsk.force', False)
profile.set_preference('browser.download.manager.alertOnEXEOpen', False)
profile.set_preference('browser.download.manager.closeWhenDone', True)
profile.set_preference('browser.download.manager.showAlertOnComplete', False)
profile.set_preference('browser.download.manager.useWindow', False)
#You will need to find the content-type of your app and set it here. We are downloading a gzip file.
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream')
profile.update_preferences()

desired_cap = {
  'browser': 'Firefox',
  'browser_version': '67.0',
  'os': 'Windows',
  'os_version': '10',
  'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
  command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com:80/wd/hub',
  desired_capabilities=desired_cap, browser_profile=profile)

#Navigate to the link
driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices")

#Accept the cookie popup
test=driver.find_element_by_link_text("Got it").click()
time.sleep(2)

#Find element by class name and store in variable "element"
element = driver.find_element_by_class_name("icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
time.sleep(2)

#Click on the element to download the file
clicked = element.click()
time.sleep(2)

driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.folderList'] = 0
profile['browser.download.manager.showWhenStarting'] = false
profile['browser.download.manager.focusWhenStarting'] = false
profile['browser.download.useDownloadDir'] = true
profile['browser.helperApps.alwaysAsk.force'] = false
profile['browser.download.manager.alertOnEXEOpen'] = false
profile['browser.download.manager.closeWhenDone'] = true
profile['browser.download.manager.showAlertOnComplete'] = false
profile['browser.download.manager.useWindow'] = false
#You will need to find the content-type of your app and set it here.
profile['browser.helperApps.neverAsk.saveToDisk'] = "application/octet-stream"

caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)
caps['browser'] = 'Firefox'
caps['browser_version'] = '67.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = 'Bstack-[Ruby] Sample Test'

driver = Selenium::WebDriver.for(:remote,
  :url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
  :desired_capabilities => caps)

#Navigate to the link
driver.navigate.to "https://rubygems.org/gems/selenium-webdriver"

#Click on the element to download the file
driver.find_element(:id => 'download').click

driver.quit
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.net.URL;

public class FileDownload {

    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

    public static void main(String[] args) throws Exception {

        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("os", "Windows");
        caps.setCapability("os_version", "10");
        caps.setCapability("browser", "Chrome");
        caps.setCapability("browser_version", "75.0");
        caps.setCapability("name", "Bstack-[Java] Sample Test");

        WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices");
        Thread.sleep(2000);

        //Find element by link text and store in variable "Element"
        WebElement Element = driver.findElement(By.className("icon-csv"));

        //This will scroll the page till the element is found
        jse.executeScript("arguments[0].scrollIntoView();", Element);
        jse.executeScript("window.scrollBy(0,-100)");
        Thread.sleep(1000);

        //Click on the element to download the file
        Element.click();
        Thread.sleep(2000);

        // check if file exists
        System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

        // get file properties
        System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

        // get file content. The content is Base64 encoded
        String base64EncodedFile = (String) jse.executeScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");

        //decode the content to Base64
        byte[] data = Base64.getDecoder().decode(base64EncodedFile);
        OutputStream stream = new FileOutputStream("BrowserStack%20-%20List%20of%20devices%20to%20test%20on.csv");
        stream.write(data);
        stream.close();

        driver.quit();
    }
}
const {Builder, By, Key, until} = require('selenium-webdriver');
const fs = require("fs");

// Input capabilities
let capabilities = {
    'browserName' : 'Chrome',
    'browser_version' : '75.0',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY',
    'name': 'Bstack-[Node] Sample Test'
}

async function main() {
    let driver = await new Builder()
        .usingServer('http://hub-cloud.browserstack.com/wd/hub')
        .withCapabilities(capabilities)
        .build();

    await driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices')

    const element = await driver.findElement(By.className('icon-csv'))
    await driver.executeScript('arguments[0].scrollIntoView();', element)
    await driver.executeScript('window.scrollBy(0,-200)')
    await element.click()

    // returns bool if file exists
    let val1 = await driver.executeScript('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
    console.log(val1)

    // returns hash of file properties
    await driver.executeScript('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

    // download file
    let data = await driver.executeScript('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
    let base64data = data.toString('base64');
    await fs.writeFile('BrowserStack - List of devices to test on.csv', base64data, function (err) {
      if (err) throw err;
      console.log('File created')
    });

    await driver.quit()
}
main()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Threading;

namespace SeleniumTest {
    class FileDownload {
        static void Main(string[] args) {
            IWebDriver driver;
            DesiredCapabilities capability = new DesiredCapabilities();
            capability.SetCapability("browser", "Chrome");
            capability.SetCapability("browser_version", "75.0");
            capability.SetCapability("os", "Windows");
            capability.SetCapability("os_version", "10");
            capability.SetCapability("browserstack.user", "YOUR_USERNAME");
            capability.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
            capability.SetCapability("name", "Bstack-[C_sharp] Sample Test");

            driver = new RemoteWebDriver(
                new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
            );
            IJavaScriptExecutor jse = (IJavaScriptExecutor) driver;

            driver.Navigate().GoToUrl("https://www.browserstack.com/test-on-the-right-mobile-devices");
            Thread.Sleep(2000);

            //Find element by link text and store in variable "Element"             
            IWebElement Element = driver.FindElement(By.ClassName("icon-csv"));

            //This will scroll the page till the element is found       
            jse.ExecuteScript("arguments[0].scrollIntoView();", Element);
            jse.ExecuteScript("window.scrollBy(0,-100)");
            Thread.Sleep(2000);

            Element.Click();
            Thread.Sleep(2000);

            // check if file exists
            bool val1 = (bool) jse.ExecuteScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            Console.WriteLine(val1);

            // get file properties
            Console.WriteLine(jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

            // download the file locally
            jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            string base64encode = (string) jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            byte[] b = Convert.FromBase64String(base64encode);
            File.WriteAllBytes(@"/<path-to-destination-folder>/BrowserStack - List of devices to test on.csv", b);
            Thread.Sleep(2000);

            driver.Quit();
        }
    }
}
from selenium
import webdriver
import time
import base64

desired_cap = {
    'browser': 'Chrome',
    'browser_version': '75.0',
    'os': 'Windows',
    'os_version': '10',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor = 'http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
    desired_capabilities = desired_cap)

driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices")
time.sleep(2)

# Accept the cookie popup
driver.find_element_by_link_text("Got it").click()
time.sleep(2)

# Find element by class name and store in variable "Element"
element = driver.find_element_by_class_name("icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
time.sleep(2)

# Click on the element to download the file
element.click()
time.sleep(2)

# check if file exists
file_exists = driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
print file_exists

# get file properties
file_properties = driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

# print file properties hash
print file_properties

# download file
get_file_content = driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
time.sleep(2)

# decode the content to Base64 and write to a file
data = base64.b64decode(get_file_content)
f = open("BrowserStack - List of devices to test on.csv", "wb")
f.write(data)

driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'Chrome'
caps['browser_version'] = '75.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = '[Bstack-[Ruby] Sample Test'

driver = Selenium::WebDriver.for(: remote,: url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",: desired_capabilities => caps)
driver.navigate.to "https://www.browserstack.com/test-on-the-right-mobile-devices"
sleep(2)

# Accept the cookie popup
driver.find_element(: link_text, "Got it").click

# Find element by class name and store in variable "Element"
element = driver.find_element(: class_name, "icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
sleep(2)

# Click on the element to download the file
element.click
sleep(2)

# Execute this action to click "Save File"
button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
sleep(2)

# check if file exists
file_exists = driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

#return bool if file exists or not
puts(file_exists)

# get file properties
file_properties = driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')# print file properties hash
puts(file_properties)

# get file content.The content is Base64 encoded
get_file_content = driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

# decode the content to Base64
decoded_content = Base64.decode64(get_file_content);
f = File.open("BrowserStack - List of devices to test on.csv", "wb")
f.write(decoded_content)
f.close

driver.quit
if driver
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.net.URL;

public class FileDownload {

    public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
    public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
    public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

    public static void main(String[] args) throws Exception {

        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("os", "Windows");
        caps.setCapability("os_version", "10");
        caps.SetCapability("browser", "IE");
        caps.SetCapability("browser_version", "11.0");
        caps.setCapability("name", "Bstack-[Java] Sample Test");

        WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices");
        Thread.sleep(2000);
        //Find element by link text and store in variable "Element"
        WebElement Element = driver.findElement(By.className("icon-csv"));

        //This will scroll the page till the element is found
        jse.executeScript("arguments[0].scrollIntoView();", Element);
        jse.executeScript("window.scrollBy(0,-100)");
        Thread.sleep(1000);

        //Click on the element to download the file
        Element.click();
        Thread.sleep(2000);

        //Execute this action to click "Save File" button in the browser prompt
        jse.executeScript("browserstack_executor: {\"action\": \"saveFile\"}");
        Thread.sleep(2000);

        // check if file exists
        System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

        // get file properties
        System.out.println(jse.executeScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

        // get file content. The content is Base64 encoded
        String base64EncodedFile = (String) jse.executeScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");

        //decode the content to Base64
        byte[] data = Base64.getDecoder().decode(base64EncodedFile);
        OutputStream stream = new FileOutputStream("BrowserStack%20-%20List%20of%20devices%20to%20test%20on.csv");
        stream.write(data);
        stream.close();

        driver.quit();
    }
}
const {Builder, By, Key, until} = require('selenium-webdriver');
const fs = require("fs");

// Input capabilities
let capabilities = {
    'browserName' : 'IE',
    'browser_version' : '11.0',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY',
    'name': 'Bstack-[Node] Sample Test'
}

async function main() {
    let driver = await new Builder()
        .usingServer('http://hub-cloud.browserstack.com/wd/hub')
        .withCapabilities(capabilities)
        .build();

    await driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices')

    const element = await driver.findElement(By.className('icon-csv'))
    await driver.executeScript('arguments[0].scrollIntoView();', element)
    await driver.executeScript('window.scrollBy(0,-200)')
    await element.click()

    // Execute this action to click "Save File" button in the browser prompt
    await driver.executeScript('browserstack_executor: {"action": "saveFile"}')

    // returns bool if file exists
    let val1 = await driver.executeScript('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
    console.log(val1)

    // returns hash of file properties
    await driver.executeScript('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

    // download file
    let data = await driver.executeScript('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
    let base64data = data.toString('base64');
    await fs.writeFile('BrowserStack - List of devices to test on.csv', base64data, function (err) {
      if (err) throw err;
      console.log('File created')
    });

    await driver.quit()
}
main()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Threading;

namespace SeleniumTest {
    class FileDownload {
        static void Main(string[] args) {
            IWebDriver driver;
            DesiredCapabilities capability = new DesiredCapabilities();
            capability.SetCapability("browser", "IE");
            capability.SetCapability("browser_version", "11.0");
            capability.SetCapability("os", "Windows");
            capability.SetCapability("os_version", "10");
            capability.SetCapability("browserstack.user", "YOUR_USERNAME");
            capability.SetCapability("browserstack.key", "YOUR_ACCESS_KEY");
            capability.SetCapability("name", "Bstack-[C_sharp] Sample Test");

            driver = new RemoteWebDriver(
                new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
            );
            IJavaScriptExecutor jse = (IJavaScriptExecutor) driver;

            driver.Navigate().GoToUrl("https://www.browserstack.com/test-on-the-right-mobile-devices");
            Thread.Sleep(2000);

            //Find element by link text and store in variable "Element"             
            IWebElement Element = driver.FindElement(By.ClassName("icon-csv"));

            //This will scroll the page till the element is found       
            jse.ExecuteScript("arguments[0].scrollIntoView();", Element);
            jse.ExecuteScript("window.scrollBy(0,-100)");
            Thread.Sleep(2000);

            Element.Click();
            Thread.Sleep(2000);

            jse.ExecuteScript("browserstack_executor: {\"action\": \"saveFile\"}");
            Thread.Sleep(2000);

            // check if file exists
            bool val1 = (bool) jse.ExecuteScript("browserstack_executor: {\"action\": \"fileExists\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            Console.WriteLine(val1);

            // get file properties
            Console.WriteLine(jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileProperties\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}"));

            // download the file locally
            jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            string base64encode = (string) jse.ExecuteScript("browserstack_executor: {\"action\": \"getFileContent\", \"arguments\": {\"fileName\": \"BrowserStack - List of devices to test on.csv\"}}");
            byte[] b = Convert.FromBase64String(base64encode);
            File.WriteAllBytes(@"/<path-to-destination-folder>/BrowserStack - List of devices to test on.csv", b);            Thread.Sleep(2000);

            driver.Quit();
        }
    }
}
from selenium
import webdriver
import time
import base64

desired_cap = {
    'browser': 'IE',
    'browser_version': '11.0',
    'os': 'Windows',
    'os_version': '10',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor = 'http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com:80/wd/hub',
    desired_capabilities = desired_cap)

driver.get("https://www.browserstack.com/test-on-the-right-mobile-devices")
time.sleep(2)

# Accept the cookie popup
driver.find_element_by_link_text("Got it").click()
time.sleep(2)

# Find element by class name and store in variable "Element"
element = driver.find_element_by_class_name("icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
time.sleep(2)

# Click on the element to download the file
element.click()
time.sleep(2)

# Execute this action to click "Save File" button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
time.sleep(2)

# check if file exists
file_exists = driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
print file_exists

# get file properties
file_properties = driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

# print file properties hash
print file_properties

# download file
get_file_content = driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')
time.sleep(2)

# decode the content to Base64 and write to a file
data = base64.b64decode(get_file_content)
f = open("BrowserStack - List of devices to test on.csv", "wb")
f.write(data)

driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'IE'
caps['browser_version'] = '11.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['nativeEvents'] = 'true'
caps['name'] = 'Bstack-[Ruby] Sample Test'


driver = Selenium::WebDriver.for(: remote,: url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",: desired_capabilities => caps)
driver.navigate.to "https://www.browserstack.com/test-on-the-right-mobile-devices"
sleep(2)

# Accept the cookie popup
driver.find_element(: link_text, "Got it").click

# Find element by class name and store in variable "Element"
element = driver.find_element(: class_name, "icon-csv")
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("window.scrollBy(0,-100)")
sleep(2)

# Click on the element to download the file
element.click
sleep(2)

# Execute this action to click "Save File"
button in the browser prompt
driver.execute_script('browserstack_executor: {"action": "saveFile"}')
sleep(2)

# check
if file exists
file_exists = driver.execute_script('browserstack_executor: {"action": "fileExists", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

# return bool if file exists or not
puts(file_exists)

# get file properties
file_properties = driver.execute_script('browserstack_executor: {"action": "getFileProperties", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')# print file properties hash
puts(file_properties)

# get file content.The content is Base64 encoded
get_file_content = driver.execute_script('browserstack_executor: {"action": "getFileContent", "arguments": {"fileName": "BrowserStack - List of devices to test on.csv"}}')

# decode the content to Base64
decoded_content = Base64.decode64(get_file_content);
f = File.open("BrowserStack - List of devices to test on.csv", "wb")
f.write(decoded_content)
f.close

driver.quit
if driver

We're sorry to hear that. Please share your feedback so we can do better






Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked





Thank you for your valuable feedback