October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Download Files to a Specific Path in Headless Chrome

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set the download directory before starting the browser, then wait for a completion signal before closing it. Selenium uses Chrome’s download.default_directory preference; Puppeteer and the Chrome DevTools Protocol (CDP) use an allowed download policy plus downloadPath. Use an absolute, writable directory that Chrome does not treat as a protected system location.

Choose the control layer first

The correct configuration depends on the automation API already in your project.

Automation layer Directory configuration Completion signal Best fit
Selenium with ChromeDriver Chrome preference download.default_directory in ChromeOptions Poll the destination or use your test framework’s download event Existing WebDriver suites
Puppeteer Browser-context setDownloadBehavior with policy: 'allow' and downloadPath Wait for the download object or for a finished file Node.js browser automation
Raw CDP Browser.setDownloadBehavior with behavior: 'allow' and downloadPath Browser.downloadProgress with state: 'completed' Direct protocol clients and custom runners

Configure the policy before clicking the link or invoking JavaScript that starts the download. Headless mode does not select a directory automatically.

Prepare a safe destination

  1. Create a unique directory before launching Chrome. A per-test or per-job directory prevents two downloads from being confused.
  2. Resolve it to an absolute path. Relative paths can be interpreted relative to an unexpected working directory.
  3. Make sure the operating-system account running Chrome can create and write files there.
  4. Avoid Desktop and other system-special locations. ChromeDriver documentation specifically warns that some paths are disallowed, including the home directory on Linux; the exact protected set can change.
  5. Use platform-native separators. On Windows, ChromeDriver recommends backslash path separators (for example, C:automationdownloads).

Selenium and ChromeDriver

Python: set the preference before navigation

This example creates an absolute directory, starts headless Chrome, clicks a link, and waits until Chrome has renamed the temporary download file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
from pathlib import Path
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

out = Path('/tmp/chrome-downloads').resolve()
out.mkdir(parents=True, exist_ok=True)

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_experimental_option('prefs', {
    'download.default_directory': str(out),
    'download.prompt_for_download': False,
    'download.directory_upgrade': True,
})

driver = webdriver.Chrome(options=options)
try:
    driver.get('https://example.test/page-with-download')
    driver.find_element(By.CSS_SELECTOR, 'a[data-download]').click()

    deadline = time.time() + 90
    previous_sizes = {}
    while time.time() < deadline:
        partial = list(out.glob('*.crdownload'))
        finished = [p for p in out.iterdir() if p.is_file() and p.suffix != '.crdownload']
        if finished and not partial:
            stable = True
            for path in finished:
                size = path.stat().st_size
                if previous_sizes.get(path) != size:
                    stable = False
                previous_sizes[path] = size
            if stable:
                print('Downloaded:', finished)
                break
        time.sleep(0.5)
    else:
        raise TimeoutError('Download did not finish within 90 seconds')
finally:
    driver.quit()

The --headless=new flag selects the current unified headless implementation in Chrome versions that support it. The preference must be present when the driver starts; setting it after the click is too late.

Java: the ChromeDriver preference

ChromeDriver’s documented setup uses a full path in ChromeOptions:

Map<String, Object> prefs = new HashMap<>();
prefs.put('download.default_directory', '/tmp/chrome-downloads');
ChromeOptions options = new ChromeOptions();
options.addArguments('--headless=new');
options.setExperimentalOption('prefs', prefs);
WebDriver driver = new ChromeDriver(options);

Create the directory and add an explicit completion check before calling driver.quit(). ChromeDriver does not automatically wait for a download to complete, so quitting immediately can leave a partial .crdownload file or no usable file at all.

How to decide that Selenium’s file is complete

For ordinary downloads, Chrome writes a temporary file ending in .crdownload and removes that suffix when the transfer finishes. A robust waiter should require both that no temporary file remains and that the final file’s size is stable across at least two checks. A fixed short sleep is not reliable when the server or network is slow. If the site supplies a known filename, wait for that exact path; otherwise record the directory contents before clicking and accept only a new file.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Puppeteer

Allow downloads in the browser context

Puppeteer’s current download behavior API is configured on a browser context. The path is required when the policy is allow or allowAndName. Check the API version installed in your project because this interface is versioned.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import puppeteer from 'puppeteer';
import fs from 'node:fs/promises';
import path from 'node:path';

const downloadPath = path.resolve('/tmp/puppeteer-downloads');
await fs.mkdir(downloadPath, { recursive: true });

const browser = await puppeteer.launch({ headless: true });
try {
  const context = browser.defaultBrowserContext();
  await context.setDownloadBehavior({
    policy: 'allow',
    downloadPath,
  });

  const page = await context.newPage();
  await page.goto('https://example.test/page-with-download', {
    waitUntil: 'networkidle2',
  });
  const before = new Set(await fs.readdir(downloadPath));
  await page.click('a[data-download]');

  const deadline = Date.now() + 90_000;
  let file;
  while (Date.now() < deadline) {
    const names = await fs.readdir(downloadPath);
    const candidates = names.filter(name => !before.has(name) && !name.endsWith('.crdownload'));
    const partial = names.some(name => name.endsWith('.crdownload'));
    if (candidates.length && !partial) {
      const candidate = path.join(downloadPath, candidates[0]);
      const first = (await fs.stat(candidate)).size;
      await new Promise(resolve => setTimeout(resolve, 500));
      const second = (await fs.stat(candidate)).size;
      if (first === second) {
        file = candidate;
        break;
      }
    }
    await new Promise(resolve => setTimeout(resolve, 500));
  }
  if (!file) throw new Error('Download timed out');
  console.log(`Downloaded ${file}`);
} finally {
  await browser.close();
}

Choosing a Puppeteer policy

  • deny blocks downloads.
  • allow permits downloads and lets Chrome use the server-suggested filename.
  • allowAndName permits downloads but names files with download GUIDs, useful when you need collision-free names and will store your own metadata.
  • default leaves the browser’s default behavior in place and is not suitable when a deterministic destination is required.

If your installed Puppeteer exposes a different method or context API, use that version’s reference and keep the same rules: configure before the click, provide an absolute writable path, and wait for completion.

Raw Chrome DevTools Protocol

Use the Browser domain for new code

Send Browser.setDownloadBehavior with behavior: 'allow' and an absolute downloadPath. Set eventsEnabled: true when you want protocol-level progress events. The Browser domain also supports allowAndName.

{
  "method": "Browser.setDownloadBehavior",
  "params": {
    "behavior": "allow",
    "downloadPath": "/tmp/cdp-downloads",
    "eventsEnabled": true
  }
}

Listen for Browser.downloadProgress. Track the guid from the corresponding Browser.downloadWillBegin event and treat state: 'completed' as the completion condition. Do not assume that the event’s filePath is populated or that a path reported by the protocol already exists; verify the file on disk.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Node.js CDP client example

With a Chrome process started using --remote-debugging-port=9222, the following uses the chrome-remote-interface package (install it with npm install chrome-remote-interface):

import CDP from 'chrome-remote-interface';
import fs from 'node:fs/promises';

const downloadPath = '/tmp/cdp-downloads';
await fs.mkdir(downloadPath, { recursive: true });
const client = await CDP({ port: 9222 });
const { Browser, Page } = client;
await Browser.setDownloadBehavior({
  behavior: 'allow',
  downloadPath,
  eventsEnabled: true,
});
await Page.enable();
Browser.downloadProgress(({ guid, state, filePath }) => {
  if (state === 'completed') {
    console.log('Completed', guid, filePath ?? '(verify the directory)');
  }
  if (state === 'canceled') console.error('Canceled', guid);
});
await Page.navigate({ url: 'https://example.test/page-with-download' });
// Issue Page.click or another Page command here, then keep the connection open
// until the completed event arrives and verify the resulting file on disk.

The older Page.setDownloadBehavior method is still visible in some protocol references, but it is experimental. Page-level download events are deprecated in favor of Browser events, so use the Browser domain for new implementations.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Headless Chrome versions

Since Chrome 112, ordinary headless Chrome shares the browser implementation with headful Chrome while creating platform windows without displaying them. From Chrome 132.0.6793.0, the old headless implementation is available only as a separate chrome-headless-shell binary. Your download configuration still belongs in Selenium preferences, Puppeteer’s context policy, or CDP regardless of which headless executable you run.

For reproducible CI, pin compatible browser and driver binaries. Chrome for Testing publishes versioned downloads through its npm utility and JSON endpoints; align the ChromeDriver version with the Chrome binary used by the job.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting

No file appears

  • Cause: The preference or policy was applied after the click. Fix: configure it immediately after creating the driver or context and before navigation that triggers the download.
  • Cause: The directory is relative, missing, or not writable by the Chrome user. Fix: resolve an absolute path, create it first, and check permissions inside the same container or service account.
  • Cause: Chrome rejected a protected location. Fix: move the destination to a dedicated temporary or workspace directory rather than Desktop, the Linux home directory, or another system-special path.

The script exits with a partial file

Do not use sleep(1) as the only wait. Poll for the disappearance of .crdownload and stable file size, or use CDP’s completed event and then verify the file. Delay driver.quit() or browser.close() until that check succeeds.

The filename is unpredictable

Servers can provide a filename through HTTP headers, and Chrome may add a suffix when a name already exists. Snapshot the directory before starting, identify the new file afterward, and move it to your application’s final name only after completion. With CDP or Puppeteer, choose allowAndName when GUID-based names are preferable to server suggestions.

Downloads work headed but not headless

Check that you are using the same Chrome binary and automation configuration in both modes. Headless does not inherit a visible browser profile’s download directory. Set the path explicitly and ensure the click is not blocked by a user-gesture or permission check in the page.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

CDP reports completion but the path is absent

The protocol warns that a reported path is not guaranteed to be set or to exist. Treat the event as a transfer-state signal, then scan the configured directory and verify file existence and size before consuming the file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Driver and browser versions disagree

A mismatched driver can fail before any download setting is applied. Pin compatible Chrome and ChromeDriver releases, or use a Chrome for Testing channel whose browser and driver artifacts are versioned together.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability, performance and security notes

  • Use one directory per concurrent job. Shared directories create races when two files have the same suggested name.
  • Set a deadline based on the largest expected file and network conditions, not an arbitrary short delay. Keep polling intervals modest (for example, 250–1,000 ms) to avoid busy-waiting.
  • Record the URL, expected content type, final path and byte count. A successful transfer event does not prove that the server returned the file your test expected.
  • Clean temporary directories after the test, but only after downstream processing has closed the file.
  • Treat downloaded content as untrusted. Do not execute it automatically, and isolate browser and file permissions in CI containers.
  • If the site requires authentication, establish the session before the click or provide the required cookies and headers through the automation framework; a download URL copied without its session may return an HTML login page.

Or skip the browser setup

If what you need is a rendered image or PDF of a page rather than the original attachment, ScreenshotNeo can return it from one API request. It is not a replacement for downloading arbitrary files, but it avoids maintaining a headless browser for screenshots and PDFs.

ScreenshotNeo accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients.

cURL

See the ScreenshotNeo API documentation for parameters and response details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G 'https://api.screenshotneo.com/v1/shot' -d access_key=YOUR_API_KEY --data-urlencode 'url=https://stripe.com' -o shot.webp

Python

import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
r.raise_for_status()
open('shot.webp', 'wb').write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await Bun.write('shot.webp', res);

Every feature is available on every plan: full-page shots with lazy images loaded, element capture by CSS selector, dark mode, device presets or custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture for up to 100 URLs per call, a usage API and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work, which can simplify migration.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000 and Business $249 for 1,000,000. Yearly billing provides two months free. Create a free ScreenshotNeo account to start without a card.

Frequently Asked Questions

Can I use the same download directory for parallel browser contexts?

Use separate directories instead. Chrome can rename colliding files, making it difficult to associate a completed file with the job that requested it.

Does setting a download path change the server’s filename?

No. The path chooses the directory; the server’s filename and Chrome’s collision rules still apply unless you use GUID naming or rename the completed file yourself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is ScreenshotNeo suitable for downloading a ZIP or installer?

No. ScreenshotNeo returns rendered screenshots or PDFs. Use Selenium, Puppeteer or CDP when you need the original binary attachment.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.