File download with headless automation

1_aoUGQKFGoplkAYSbPv8i5g

      In selenium headless automation, we had a scenario to download a file and verify the file content. We tried with chrome browser as headless for execution but failed to download the file into a respective path mentioned in the ChromeOptions via setExperimentalOption. 

     Finally, we derived a solution to download the file into respective path when the application under headless execution. We used to send the Page.setDownloadBehavior value as a request. This request needs to execute after the headless driver instantiation. Following is the sample code snippet which helped us to solve the file download issue under headless automation execution,

String dowloadPath = “directory path to your file to download”;

System.setProperty(“webdriver.chrome.driver”, “path to chromedriver.exe”);

ChromeOptions options = new ChromeOptions();
options.addArguments(“–test-type”);
options.addArguments(“–headless”);
options.addArguments(“–disable-extensions”);
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver driver = new ChromeDriver(driverService, options);

Map<String, Object> commandParams = new HashMap<>();
commandParams.put(“cmd”, “Page.setDownloadBehavior”);
Map<String, String> params = new HashMap<>();
params.put(“behavior”, “allow”);
params.put(“downloadPath”, dowloadPath);
commandParams.put(“params”, params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + “/session/” + driver.getSessionId() + “/chromium/send_command”;
HttpPost request = new HttpPost(u);
request.addHeader(“content-type”, “application/json”);
request.setEntity(new StringEntity(command));
httpClient.execute(request);

     Try to use the above code snippet if you are facing the file download issue during headless automation execution.

make it perfect!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s