The only sure way to upload and download files in Selenium tests

image


Selenium WebDriver was created as a cross-platform tool for managing web browsers. And for almost 14 years now he has been doing this work very, very well. However, real-world autotests create situations in which Selenium is powerless. For example, according to a script, you need to upload or download a file. After clicking the "Download" or "Download" button, a window of the file manager of the operating system appears on top of the browser window to which Selenium no longer has access. The test stops.


I heard recommendations to use utilities like AutoIt or Sikuli to work with such system windows. My advice is to never do this, this is a vicious practice that leads to unstable tests:


  • -. .
  • . , .
  • headless

. 15 8 . .


— , .



, . — "". , ( input file) sendKeys() "" :


By fileInput = By.cssSelector("input[type=file]");
String filePath = "/home/selenium/files/upload.txt";

driver.findElement(fileInput).sendKeys(filePath);

. Selenium . . . , , , .


, ? , , DOM . $$("input[type=file]")


image


, findElement() . . , . , .


image


Selenium

, . , Selenium , . — . (barancev) . , .



, . - , Downloads, Selenium ( Internet Explorer), "" .


, , :


image


, . . :


image


, . href . , , http . Java :


//Get download link 
String downloadLink = driver
         .findElement(By.cssSelector("main#content a.btn"))
         .getAttribute("href");

//Set file to save
File fileToSave = new File("/path/to/file.zip");

//Download file using default org.apache.http client 
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(downloadLink);
HttpResponse response = httpClient.execute(httpGet, new BasicHttpContext());

//Save file on disk
copyInputStreamToFile(response.getEntity().getContent(), fileToSave);

http

, . , JavaScript . , . , , , . , . , - . , , Selenium. BrowserUpProxy BrowserMobProxy.


, Selenide. DownloadFileWithProxyServer.


, , . https, .


, , . , . — .



In order for the tests to remain stable, factors that make them fragile must be removed. Dialogs of an operating system, it is one of such factors. In the following articles I plan to reveal other important aspects that greatly affect the stable operation of Selenium tests. Listen to the QA Guild podcast and good automation.


All Articles