Skip to content
CodeKruPro

Automation tool (Selenium) · Java

Screenshots, uploads and downloads

Screenshots, file uploads, downloads and cookies.

Learn: Screenshots, uploads, downloads and cookies in Selenium Java7 minute read

This topic gathers the "can Selenium do X?" questions: screenshots, uploading and downloading files, cookies, test sites with bad certificates, and broken links. Each answer is short once you know which API to use and where Selenium stops. Interviewers use these questions to see whether you have built real suites, so one practical detail per answer helps a lot.

Screenshots

A screenshot is the main evidence in a failure report. The driver implements the TakesScreenshot interface, so you cast to it:

File page = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(page.toPath(), Paths.get("target/screens/home.png"), StandardCopyOption.REPLACE_EXISTING);

byte[] png = driver.findElement(By.id("chart")).getScreenshotAs(OutputType.BYTES);

OutputType.FILE gives a temporary PNG file that you copy somewhere safe. BYTES is handy for attaching to reports, and BASE64 suits HTML reports. WebElement also extends TakesScreenshot, so you can capture one element. A normal screenshot shows the viewport, the part of the page visible in the window, not the whole page. A built-in full-page screenshot exists only for Firefox. In a framework, a listener (code that the test framework calls automatically, here when a test fails) takes the screenshot.

Uploading a file

Selenium cannot use the operating system's file dialog, and it does not need to. Send the absolute path to the file input:

Path file = Paths.get("src/test/resources/report.pdf").toAbsolutePath();
driver.findElement(By.cssSelector("input[type='file']")).sendKeys(file.toString());
driver.findElement(By.id("upload")).click();

The input then shows a value like C:\fakepath\report.pdf. That is a browser privacy rule, not an error. If the input is hidden behind a styled button, target the input itself.

On Selenium Grid (a setup that runs browsers on other machines; see Grid) the browser runs on another machine (a node) that does not have your file. A file detector decides whether the text you send is a path to a local file and, if it is, copies that file to the node. In Java, RemoteWebDriver uses a UselessFileDetector by default, which sends nothing, so add one line before the upload:

((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());

Downloading and checking a file

Locally, tell Chrome where to save files and not to ask:

Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadDir.toAbsolutePath().toString());
prefs.put("download.prompt_for_download", false);
options.setExperimentalOption("prefs", prefs);

Click the link, then wait with a custom condition until the file exists and no temporary .crdownload file remains. Then check its size or content. On Grid the file lands on the node, so set options.setEnableDownloads(true); ((HasDownloads) driver).getDownloadedFiles() lists the files and downloadFile(name, targetDir) copies one back.

Cookies

A cookie is a small named value the site stores in the browser, such as a session id.

driver.get("https://shop.example.test/");
driver.manage().addCookie(new Cookie("session_id", token));
driver.navigate().refresh();
Cookie c = driver.manage().getCookieNamed("session_id");   // null if missing
driver.manage().deleteAllCookies();

You can add a cookie only for the domain of the page you are on; another domain throws InvalidCookieDomainException. A common speed-up is to log in through the API, add the session cookie, and skip the login screen in most tests.

Invalid certificates and broken links

Test environments often use self-signed certificates (a certificate that the site made for itself, so browsers do not trust it), which browsers reject with a privacy error page. options.setAcceptInsecureCerts(true) lets the test continue; keep it to test environments. For broken links, remember that Selenium does not see HTTP status codes (the number a server returns, such as 200 for OK or 404 for not found). Collect every href, remove duplicates and non-HTTP links, and check each with java.net.http.HttpClient. A status of 400 or above is broken.

How to answer in an interview

Give the API in one line, then the detail that shows experience: copy the screenshot file out of the temp folder, upload by path without the dialog, set the file detector on Grid, wait for the .crdownload file to disappear, open the domain before adding a cookie.

Common mistakes

  • Clicking the upload button and trying to type into the dialog.
  • Expecting a full-page screenshot from Chrome.
  • Checking a download the moment the click returns, before the file is complete.
  • Adding a cookie before opening any page of that domain.
  • Trying to read status codes with Selenium alone.

Recap

Screenshots: cast to TakesScreenshot, viewport only. Uploads: send the path to the file input, plus LocalFileDetector on Grid. Downloads: set a folder and wait for the finished file. Cookies: open the domain first. Status codes need an HTTP client.

11 questions0/11 solved

StatusQuestionDifficultyAsked in
Not startedUpload a file without the file dialogEasy-MediumAsked in: TCS
Not startedTaking a screenshot in Selenium JavaEasy-MediumAsked in: Capgemini, Infosys, TCS +1
Not startedSave a screenshot of the viewportEasy-MediumAsked in: Capgemini, Infosys, TCS +1
Not startedSave a screenshot of one elementMediumAsked in: Capgemini, Infosys, TCS +1
Not startedAdd, read and delete a cookieMediumAsked in: Infosys
Pro+Uploading a file when the browser runs on Grid (Java)Medium-HardAsked in: Accenture, Capgemini, Infosys +1
Pro+Download a file and verify it arrived (Java)Medium-Hard
Pro+Find every broken link on a page (Java)MediumAsked in: Accenture, Capgemini, Cognizant +3
Pro+Open a test site with an invalid SSL certificate (Java)MediumAsked in: Infosys
Pro+Adding a cookie for another domainMediumAsked in: Infosys
Pro+Does Selenium have a full-page screenshot?MediumAsked in: Capgemini, Infosys, TCS +1
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan