Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
3.7k views
by The go-to Tester (222 points)
I have a program that helps me download a file on local machine. How do I do it on the browserstack?

2 Answers

1 like 0 dislike
by

We can not really download a file to the local machine from either BrowserStack, SauceLabs or your internal grid. Because, when the file is downloaded it usually stores in the local machine at the set downloaded location.

If you want to download a file to your local machine where your code is getting executed from, we can use cookies and HTTP get classes to download the file.

You can navigate to the page using Selenium WebDriver where your file can be downloaded. I assume that you have the login page which you entered your login credentials. When you log in, it generates cookies. You can use those cookies to download file using HTTPGet

Check below example:

import in.mayurshah.DTO.WebDriverConfig;
import in.mayurshah.base.xRemoteWebDriver;
import in.mayurshah.util.Log;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.ContentEncodingHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Set;

public class SampleFileDownload {
    private WebDriver driver;
    private SampleFileDownload () throws IOException {
        WebDriverConfig webDriverConfig = new WebDriverConfig();
        webDriverConfig.setRemoteURL(null);
        webDriverConfig.setOS(null);
        webDriverConfig.setBrowserName("chrome");
        webDriverConfig.setBrowserVersion("*");
        webDriverConfig.setIntenal(true);
        driver = xRemoteWebDriver.getInstance(webDriverConfig,new Log());
        driver.get("https://www.example.com/");
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        WebDriverWait wait = new WebDriverWait(driver,1500);
        wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loadingmessage")));
    }
    
    punlic void login(){
        //your login script here
    }

    public static void main(String[] args) throws IOException {
        SampleFileDownload _SampleFileDownload  = new SampleFileDownload ();
        _SampleFileDownload.login(); // when you login, it generates cookies. You can use those cookies to download file using HTTPGet
        CookieStore cookieStore = _SampleFileDownload  .seleniumCookiesToCookieStore();
        ContentEncodingHttpClient httpClient = new ContentEncodingHttpClient ();
        httpClient.setCookieStore(cookieStore);

        HttpPost httpPost = new HttpPost("https://www.example.com/services/admin/lzjob/bdsi/223138/log");

        httpPost.setHeader("Host","www.example.com");
        httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
        httpPost.setHeader("Accept","application/json, text/javascript, */*; q=0.01");
        httpPost.setHeader("Accept-Language","en-US,en;q=0.5");
        httpPost.setHeader("Accept-Encoding","gzip, deflate, br");
        httpPost.setHeader("Content-Type","application/json; charset=utf-8");
        httpPost.setHeader("X-Requested-With","XMLHttpRequest");
        httpPost.setHeader("Referer","https://www.example.com/index.html");
        httpPost.setHeader("Connection","keep-alive");
        httpPost.setHeader("Origin","https://www.example.com");

        StringBuilder stringBuilder = new StringBuilder();
        String token = null;
        List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
        for(int i = 0; i< cookies.size() ; i++) {
            stringBuilder.append(cookies.get(i).getName() + "=" + cookies.get(i).getValue() + ((i == cookies.size() - 1) ? "" : ";"));
            if(cookies.get(i).getName().equals("token"))
                token = cookies.get(i).getValue();
        }
        httpPost.setHeader("token" , token);
        System.out.println("Cookie formed for header : " + stringBuilder.toString());
        httpPost.setHeader("Cookie",stringBuilder.toString());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        InputStream inputStream = httpResponse.getEntity().getContent();


        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream,writer);
        System.out.println("String output: \n" + writer.toString() );
        inputStream.close();

    }
    private CookieStore seleniumCookiesToCookieStore() {

        Set<Cookie> seleniumCookies = driver.manage().getCookies();
        CookieStore cookieStore = new BasicCookieStore();

        for(Cookie seleniumCookie : seleniumCookies){
            //if(seleniumCookie.getName().equals("token")) {
            System.out.println("Cookie name: " + seleniumCookie.getName() + "\tCookie value: " + seleniumCookie.getValue());
                BasicClientCookie basicClientCookie =
                        new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
                basicClientCookie.setDomain(seleniumCookie.getDomain());
                basicClientCookie.setExpiryDate(seleniumCookie.getExpiry());
                basicClientCookie.setPath(seleniumCookie.getPath());
                cookieStore.addCookie(basicClientCookie);
            //}
        }
        return cookieStore;
    }
}

Using above code, you can download the file to your local machine where the code is executing. I could switch between BrowserStack, SauceLabs and the internal grid. And the code works.

0 like 0 dislike
by The go-to Tester (222 points)

Assuming that you are using the firefox browser,

To download files through the test files, you need to create a profile capability containing all the necessary parameters, and then associate it with the WebDriver.

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("browserName", "firefox");
caps.setCapability("browserstack.debug", "true");
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);

 


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

1.4k questions

1.6k answers

866 comments

1.9k users

...