Skip to content
CodeKruPro

Automation tool (Selenium) · Python

Screenshots, uploads and downloads

Screenshots, file uploads, downloads and cookies.

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

"Can Selenium take a screenshot, upload a file, check a download, use cookies?" These questions come as a group. Each has a short API answer plus one detail that shows you have done it in a real suite, and that detail is what interviewers listen for.

Screenshots

A screenshot is the main evidence when a test fails.

driver.save_screenshot("home.png")                  # returns True
png_bytes = driver.get_screenshot_as_png()          # for reports
text = driver.get_screenshot_as_base64()
driver.find_element(By.ID, "chart").screenshot("chart.png")

Screenshots are PNG files. save_screenshot with a name that does not end in .png still writes PNG data and warns you. A normal screenshot covers the viewport, the part of the page visible in the window. A built-in full-page screenshot exists only for the Firefox driver. In a pytest framework, take the screenshot in a failure hook (a pytest function that runs when a test fails) and attach the bytes to the report instead of saving files in every test.

Uploading a file

Do not open the file dialog; Selenium cannot use it. Send the absolute path to the file input:

from pathlib import Path

file = Path("data/report.pdf").resolve()
driver.find_element(By.CSS_SELECTOR, "input[type='file']").send_keys(str(file))
driver.find_element(By.ID, "upload").click()

The input then reports a value like C:\fakepath\report.pdf, which is normal browser behaviour. On Selenium Grid (a setup that runs browsers on other machines; see Grid) the browser runs on another machine (a node). 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. webdriver.Remote uses a LocalFileDetector by default, so Python copies the file to the node for you. Java needs one extra line for this, a nice detail to mention.

Downloading and checking a file

options.add_experimental_option("prefs", {
    "download.default_directory": str(download_dir),
    "download.prompt_for_download": False,
})

After the click, wait until the file is complete. Chrome writes a temporary .crdownload file while downloading:

WebDriverWait(driver, 30).until(
    lambda d: (download_dir / "report.csv").exists()
    and not list(download_dir.glob("*.crdownload")))

Then check the size or read the content, for example with the csv module. pytest's tmp_path fixture gives every test its own empty folder, which avoids clashes in parallel runs. On Grid, set options.enable_downloads = True; driver.get_downloadable_files() lists files on the node and driver.download_file(name, target_dir) copies one to your machine.

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.add_cookie({"name": "session_id", "value": token})
driver.refresh()
cookie = driver.get_cookie("session_id")     # a dict, or None
driver.delete_all_cookies()

Cookies can be added only for the domain of the current page; another domain raises InvalidCookieDomainException. Logging in through an API and adding the session cookie skips the login screen and speeds up a suite.

Invalid certificates and broken links

For test environments with self-signed certificates (a certificate that the site made for itself, so browsers do not trust it), set options.accept_insecure_certs = True before starting the driver. Never turn off certificate checks for the whole machine. For broken links, Selenium collects the links and an HTTP client checks them, because Selenium cannot read status codes (the number a server returns, such as 200 for OK or 404 for not found):

import requests      # third-party

links = {a.get_attribute("href") for a in driver.find_elements(By.TAG_NAME, "a")}
broken = []
for url in sorted(u for u in links if u and u.startswith("http")):
    code = requests.head(url, allow_redirects=True, timeout=10).status_code
    if code == 405:                      # HEAD not allowed
        code = requests.get(url, allow_redirects=True, timeout=10).status_code
    if code >= 400:
        broken.append(f"{url} {code}")
assert not broken, "Broken links: " + ", ".join(broken)

How to answer in an interview

Give the API, then one practical detail: screenshots in a failure hook before the driver quits, uploads by path, waiting for the .crdownload file to go, opening the domain before adding a cookie, and an HTTP client for status codes.

Common mistakes

  • Clicking the upload button and trying to type into the dialog.
  • Expecting a full-page screenshot from Chrome.
  • Checking a download before it finishes.
  • Calling add_cookie("k", "v") with two strings; it takes one dict.

Recap

Screenshots are PNG and cover the viewport. Uploads go through the file input and work on Grid without extra code. Downloads need a folder and a wait for the finished file. Cookies need the right domain open first.

12 questions0/12 solved

StatusQuestionDifficultyAsked in
Not startedUpload a file without the file dialogEasy-MediumAsked in: TCS
Not startedTaking a screenshot in Selenium PythonEasy-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 (Python)Medium-HardAsked in: Accenture, Capgemini, Infosys +1
Pro+Download a file and verify it arrived (Python)Medium-Hard
Pro+Find every broken link on a page (Python)MediumAsked in: Accenture, Capgemini, Cognizant +3
Pro+Open a test site with an invalid SSL certificate (Python)MediumAsked in: Infosys
Pro+Adding a cookie for another domainMediumAsked in: Infosys
Pro+Cookies in Selenium PythonEasy-MediumAsked 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