EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Linux / Downloading 254 Export Files, 542 GB, Without Duplicates in Chrome
Linux

Downloading 254 Export Files, 542 GB, Without Duplicates in Chrome

by Ton-Or ·29 Nov 2026·12 min read
Downloading 254 Export Files, 542 GB, Without Duplicates in Chrome

The hard part of downloading many files through a browser is not clicking. It is knowing what the browser is actually doing before the next click, because one extra click costs 2 GB.

1-minute summary

Symptom / problem
An account data export of 254 parts and 542 GB must be clicked link by link in a logged-in browser
Who should read
People who must download many files through a logged-in browser with a CDP script
Fix in short
Check both the disk and chrome://downloads before every click, keep state on disk so it can stop and resume, and pause for a human when re-authentication is required
Jump to steps

I requested an export of my own account data from an online service (a Takeout-style job) and got back 254 parts, roughly 2 GB each, totaling 542 GB. The page had a download link for each part, accessible only in a logged-in session. After clicking through 9 parts by hand, I could already see that doing the remaining 245 manually was not going to work, so I wrote a script to drive the logged-in Chrome instance and click for me. What I thought would take an hour broke in six different ways before it settled down. Each failure came from one wrong assumption of mine, so I have laid them out in the order I encountered them.

The job IDs, account names, filenames, and ports in this article are all examples. The sizes, times, and log messages are real.

The task: 245 links in a logged-in browser

The destination was an external USB drive with 916 GB free. Chrome already had download.default_directory set to that drive. Clicking a link started the download immediately, with no save-as prompt.

The approach I chose was not to extract the URLs and download them with another tool, but to connect to the logged-in Chrome instance through CDP and have it click the actual links one part at a time. Chrome would handle the downloads just as if I had clicked them myself. The session and cookies stayed where they were. The script did not need to know anything about authentication.

Each row on the page contained a link in the form <a href=".../download?j=<JOB>&i=<เลข part ลบ 1>&...">, so the part number mapped directly from the i= value without having to infer it from the row order.

254total parts
542 GBtotal size
9parts already clicked manually
916 GBfree on the destination drive

I have already covered separating profiles and CDP ports by workload, and the problem where a port responds but commands do not work, in the article on CDP and Chrome updating itself. This is another layer: the state of the browser's download manager.

First wrong assumption: watching for a file by its part name

The first version of the script clicked and then watched the drive, waiting for a file with that part's name to appear. It never found one, because while downloading, Chrome writes to a file named something like Unconfirmed 694092.crdownload. The number is random, and nothing identifies which part it belongs to. It gets its real name only when the download finishes.

So I switched to listening for CDP events. Enabling them with Browser.setDownloadBehavior gives me Browser.downloadWillBegin and Browser.downloadProgress events. Each download has its own guid, tied to the tab where I triggered the click, without mixing in downloads from other windows writing to the same drive.

{"id": 1, "method": "Browser.setDownloadBehavior",
 "params": {"behavior": "default", "eventsEnabled": true}}

{"method": "Browser.downloadWillBegin",
 "params": {"guid": "<GUID>", "suggestedFilename": "takeout-<เวลา>-1-030.zip"}}

{"method": "Browser.downloadProgress",
 "params": {"guid": "<GUID>", "state": "inProgress",
            "receivedBytes": 1181116006, "totalBytes": 2147483648}}

behavior: default tells Chrome to download using its existing settings. I only ask it to send events as well. At the end, state changes to completed or canceled.

Where did the 2 GB (1).zip files come from?

Chrome does not overwrite files with the same name. If ...-030.zip already exists, the new file silently becomes ...-030 (1).zip, with no prompt or warning. I first ran into this after restarting the script while part 30 was downloading. The new instance scanned the drive, did not see a file for part 30 (it was still named Unconfirmed), concluded that it had not been downloaded, and clicked again. That gave me a 2 GB duplicate.

The second time involved authentication. This page periodically asks for reauthentication, with the token expiring after roughly 30 minutes. When it expired, the tab was redirected to the verification page and the running download was interrupted. Once I finished verifying, Chrome resumed the original download on its own. But my script had already counted that part as a failure, so it clicked again and produced two copies once more.

Events only report what I started

CDP download events only see downloads that began after this script connected. They do not know about downloads left over from the previous script instance, downloads Chrome resumed on its own, or downloads someone started manually in another window. Treating events alone as the truth leads to repeated clicks whenever the script's picture differs from what is actually happening in the browser.

Read the actual state from the download manager before every click

The place that knows about every download in the profile is chrome://downloads, and CDP can read it just like any other web page. I kept one tab open on this page and had the script query its list before every click. Each item has a state (0 downloading, 1 canceled, 2 complete, 3 paused, 5 interrupted), percent, progressStatusText (such as "38.1 MB/s - 1.1 GB of 2.0 GB, 24 secs left"), and a url containing i=, so I can identify the part without relying on its filename.

import json, re, urllib.request
from websocket import create_connection   # pip install websocket-client

CDP = "http://127.0.0.1:9333"

JS = """(() => {
  const m = document.querySelector('downloads-manager');
  if (!m) return [];
  return (m.items_ || []).slice(0, 60).map(d => ({
    file: d.fileName || '', state: d.state, pct: d.percent,
    status: d.progressStatusText || '', url: d.url || ''
  }));
})()"""

def chrome_downloads():
    tabs = json.load(urllib.request.urlopen(CDP + "/json", timeout=8))
    tab = next(t for t in tabs if "chrome://downloads" in t.get("url", ""))
    ws = create_connection(tab["webSocketDebuggerUrl"], timeout=10)
    try:
        ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
                            "params": {"expression": JS, "returnByValue": True}}))
        while True:
            msg = json.loads(ws.recv())
            if msg.get("id") == 1:
                break
    finally:
        ws.close()
    items = msg["result"]["result"].get("value") or []
    for d in items:
        m = re.search(r"[?&]i=(\d+)(?:&|$)", d["url"])
        d["part"] = int(m.group(1)) + 1 if m else None
    return items

def in_flight():
    """{part: รายการ} ของทุกอย่างที่ Chrome ยังเปิดอยู่ ห้ามคลิก part พวกนี้"""
    return {d["part"]: d for d in chrome_downloads()
            if d["part"] and d["state"] in (0, 3)}

items_ is an internal structure of the downloads page, not an API with a guaranteed contract. When Chrome changes the page structure, this code will need to change with it. I accepted that risk because this was a one-time job, and made it return an empty list with a warning in the log if it could not read the data.

There were two other things to fix at the same time. First, identify the download page's tab by its target id, not its URL, because the URL changes when it is redirected for authentication. Looking up the tab by URL would lose track of it. Second, reread the links' href values every time authentication finishes, because the token is embedded in the links. Links saved before that are no longer valid.

queued245 parts leftClick linkFind href by i=Nin-flightstate 0: watch percentcompleteFull file on diskStalled 90 secondspause then resumebytes changeStalled 180 secondscancel + delete partialClick againtoken expiredVerify identity[WAIT] alert, wait for userVerified: reread linksRetry part, no fail countCheck before every click: any match = do not click1 File already on disk2 In-flight in Chrome3 Another instance's lockMust exceed 100 MBstate 0 or 3Prevent concurrent instances
The lifecycle of one part: a click is allowed only after passing the three checks at the bottom. During a download, if the byte count stalls for 90 seconds, pause and resume. If it stalls for 180 seconds, cancel and go back to clicking again.

Reauthentication: wait for a person instead of counting a failure

I set a firm rule here: the script must never handle authentication. It does only three things: detect that the tab has been redirected to the verification page, stop the queue, and call someone over to do it.

def wait_for_human(tab):
    """หน้าเว็บขอยืนยันตัวตนใหม่: หยุดคิว แจ้งเตือน แล้วรอจนคนทำเสร็จ"""
    log("[WAIT] ถูกพาไปหน้ายืนยันตัวตน - หยุดคิว รอคนยืนยันที่หน้าต่าง Chrome")
    notify("งานดาวน์โหลดหยุดรอ: ต้องยืนยันตัวตนที่หน้าต่างเบราว์เซอร์")
    while at_reauth(tab):            # ดูจาก URL ของ tab ที่ผูกด้วย target id
        time.sleep(30)
    log("[AUTH] กลับมาหน้าดาวน์โหลดแล้ว")

part = next_missing_part()
while part is not None:
    ok, note = fetch_part(tab, part)
    if note == "REAUTH":
        wait_for_human(tab)
        links = href_map(tab)        # token ฝังในลิงก์ ต้องอ่านใหม่
        if part in in_flight():      # Chrome resume ตัวเดิมเอง ห้ามคลิกซ้ำ
            ok, note = wait_for_download(part)
        else:
            continue                 # ลอง part เดิมอีกรอบ ไม่นับเป็น fail
    log("[%s] part %d  %s" % ("OK" if ok else "FAIL", part, note))
    part = next_missing_part()
Passwords are not the script's job

An authentication checkpoint is where the system requires a person to be present. A good script should stop cleanly, clearly say what it is waiting for, and continue on its own once the person finishes, without damaging downloads in progress. The part that actually needs designing is "What state is Chrome in after verification?" The answer is that it resumes the original download itself, so the script must always query the download manager first.

Deleting a partial while Chrome still has the file open

Canceled downloads left .crdownload files behind. At one point, 3 files totaling roughly 4.1 GB remained, making the daemon think something was still downloading and wait indefinitely. So I added cleanup for partial files with no owner, and immediately got a new bug. It deleted a 1.80 GB Unconfirmed NNNNNN.crdownload file while Chrome was still writing to it.

My assumption was that "Windows locks files that are in use, so they cannot be deleted anyway." That was wrong. A file Chrome has open can be deleted, and that download was ruined. The cleanup code therefore needed its own guard.

ACTIVE_WINDOW = 120   # วินาที: ไฟล์ที่เพิ่งถูกเขียนภายในเวลานี้ ถือว่ายังมีคนใช้

def clean_partials(dest, flights):
    """ลบ .crdownload ที่ไม่มี download ไหนเป็นเจ้าของแล้ว"""
    for name in sorted(os.listdir(dest)):
        if not name.lower().endswith(".crdownload"):
            continue
        part = part_of(name)                 # None ถ้าเป็นชื่อ Unconfirmed
        if part and part in flights:
            continue                         # Chrome บอกว่ายังโหลดอยู่
        path = os.path.join(dest, name)
        if time.time() - os.stat(path).st_mtime < ACTIVE_WINDOW:
            continue                         # ยังถูกเขียนอยู่ ไม่ว่าของใคร
        if part is None and flights:
            continue                         # ชื่อไม่บอก part และมีของวิ่งอยู่ อย่าเสี่ยง
        os.remove(path)
        log("[CLEAN] ลบ partial ที่ถูกทิ้ง %s" % name)

The last condition there matters. An Unconfirmed filename does not say which part it belongs to, and a stalled download has an old mtime just like an abandoned file. There is no way to distinguish them. If even one download is still active, assume the file could belong to it. Wait until the queue is idle between parts before cleaning up.

Parts that are not zip files, and downloads that stall midway

My counter found existing parts using a regex for zip filenames, but some parts did not arrive as zip files. A single file larger than the chunk size was sent as the original file in full, with the part number appended to its name. I encountered .mp4 video files of 2.46 GB, 6.10 GB, and 3.93 GB. The original regex missed them, counted them as absent, and downloaded them again.

PART_RE = re.compile(r"takeout-\d{8}T\d{6}Z-\d+-(\d{3})\.zip$", re.I)
LOOSE_PART_RE = re.compile(r"-(\d{3})\.[A-Za-z0-9]{2,6}$")   # ไฟล์เดี่ยวที่ไม่ใช่ zip
MIN_OK = 100 * 1024 * 1024    # เล็กกว่านี้ไม่ใช่ part จริง

def part_of(name):
    m = PART_RE.search(name) or LOOSE_PART_RE.search(name)
    return int(m.group(1)) if m else None

def scan_disk(dest):
    """{part: (ชื่อไฟล์, ขนาด)} ของทุก part ที่ลงดิสก์ครบแล้ว"""
    have = {}
    for name in os.listdir(dest):
        if name.lower().endswith(".crdownload"):
            continue
        part = part_of(name)
        size = os.path.getsize(os.path.join(dest, name))
        if part and size >= MIN_OK:
            have[part] = (name, size)
    return have

After I added the second regex, the count immediately jumped from 78 to 81, and deleting the duplicates recovered 4.93 GB.

Midway stalls came with a numerical trap. When the byte count stopped moving, the MB/s value Chrome displayed kept gradually falling because it was a cumulative average, not the current speed. At a glance, the download looked as though it was still running, just slowly. So I watched only the byte count and set up two stages: after 90 seconds without progress, pause and resume; after 180 seconds, cancel, delete the partial, and click again.

# log จริงของ part ที่ค้าง (ตัดเลข part ออก)
stalled at 1.44 GB - pause/resume to wake it up
dead at 1.44 GB after 182s idle - cancelled, clicking again
[OK] ...  2.00 GB  (38.8 MB/s)

This part stalled at 72%. The 90-second step could not wake it up, and it was canceled at 182 seconds. The new attempt ran at 38.8 MB/s through to completion. My conclusion was that this job's signed URL did not accept Range requests to continue from the previous position, so pausing and resuming did not help in this case. The 1.44 GB already downloaded had to be discarded. I kept the 90-second step because the cost of trying it was only another 90 seconds of waiting.

What I assumed

Falling speed means it is still running

The MB/s number kept changing, so I kept waiting. A single part could take unlimited time while the rest of the queue went nowhere.

What I actually used

Watch only the bytes received

After 90 seconds with no change in bytes, try waking it up. At 180 seconds, discard it and click again, with a 90-minute limit per part as another safeguard.

The final design and this job's numbers

The principle that made everything stable was state lives on disk. A completed part is one whose complete file exists on the drive. There is no separate state file that can drift from reality. The script rescans the drive before every part, so I can stop and restart it at any time. It can also work alongside someone clicking manually in another window. The script works upward from the lowest number while the person works backward from the end (there is a --desc option to reverse direction). This is the same principle I used in resumable API batch work.

def take_lock(path):
    """กันสองตัวรันพร้อมกัน: สร้างไฟล์แบบ exclusive ถ้ามีอยู่แล้วให้ดูว่าเจ้าของยังอยู่ไหม"""
    try:
        fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        with open(path) as f:
            pid = int(f.read().strip() or 0)
        if pid and pid_alive(pid):
            sys.exit("[STOP] มีอีกตัวรันอยู่ (pid %d)" % pid)
        os.remove(path)                      # lock ค้างจากตัวที่ตายไปแล้ว
        return take_lock(path)
    os.write(fd, str(os.getpid()).encode())
    os.close(fd)

def may_click(part, dest):
    """เช็กสามข้อก่อนคลิก ข้อ 3 (lock) ผ่านมาตั้งแต่ตอนเริ่มโปรแกรม"""
    if part in scan_disk(dest):
        return False, "มีบนดิสก์แล้ว"
    if part in in_flight():
        return False, "Chrome กำลังโหลดอยู่ รอ ไม่คลิก"
    return True, ""
Constant Value Purpose
MIN_OK 100 MB Files smaller than this do not count as parts
BEGIN_WAIT 120 seconds Wait for a click to become a download
STALL_SOFT 90 seconds No byte progress -> pause then resume
STALL_LIMIT 180 seconds No byte progress -> cancel then click again
PART_CAP 90 minutes Time limit for one part
IDLE_WAIT 300 seconds Pause before retrying after consecutive failures
ACTIVE_WINDOW 120 seconds Do not delete partials newer than this

The available modes are --daemon (loop until complete), --status (read only, reporting what is on disk and what is downloading), --dry, --only 9,10, and --max N. The daemon runs through a wrapper that restarts it if it exits, in a visible console window rather than hidden as a service. Two prohibitions are written directly into the code: do not launch Chrome on its own, and do not reload the page on its own. If Chrome is not running, wait.

  1. Acquire the lock. If another instance is running, exit immediately.
  2. Scan the drive, count existing parts using both regex patterns, and exclude files smaller than 100 MB.
  3. Ask chrome://downloads what is pending. If the next part is there, keep watching it instead of clicking.
  4. Read the part's href fresh from the page, click it, and wait up to 120 seconds for downloadWillBegin.
  5. If Chrome's proposed filename contains (1), someone has already downloaded it. Cancel immediately at 0 bytes.
  6. Watch the byte count through the 90- and 180-second stages. If the authentication page appears, stop the queue, send an alert, and wait for a person.
  7. When the part finishes, rescan the drive to verify it, then clean up partials only when nothing is running.
35.9-51 MB/sspeed per part
1 minuteapproximately per part
121/254in 6 hours
250.72 GBat 123/254 when stopped
4.93 GBrecovered by deleting duplicates
1.44 GBdiscarded because it could not resume

Speed per part ranged from 35.9 to 51 MB/s, roughly one minute per file. In 6 hours, 121 of 254 parts were downloaded. Overall throughput was much lower than the speed per file, partly because the queue had to wait for a person every time reauthentication was required. I then stopped it at 123/254 (250.72 GB) to click through the remainder myself, which I could do immediately because state lived on disk.

Before trusting that the downloads were usable, I checked a sample consisting of the first 29 parts by reading each zip's central directory at the end of the file. This was quick and did not require extraction.

import sys, zipfile

total = 0
for path in sys.argv[1:]:
    with zipfile.ZipFile(path) as z:       # เปิดได้ = central directory ครบ
        infos = z.infolist()
    total += len(infos)
    print("%s  entries=%d  bytes=%d" % (path, len(infos), sum(i.file_size for i in infos)))
print("รวม", total, "entries")

The result was that every part was a complete zip in its own right, with no file spanning multiple parts. There were 31,968 entries in total, with 244 video files accounting for 47% of all bytes. That meant I could extract one part at a time without waiting for all 254.

The lesson I will carry forward is this: when driving a browser to download files, do not trust the script's picture of what is happening. Query the two actual sources before every action: the disk and the download manager. Where the system requires a person, let a person do it. Anyone adapting this structure to another website needs to rewrite the method for finding part numbers in links and the method for detecting the authentication page. The rest can stay as it is. If I have left anything unexplained, or Chrome changes the downloads page structure, I will come back and update this later.

Want us to set this up?

Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.

Get a quote

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first