← blog  /  tools

Download all files from a website in Python: 964 file links and the traps we measured

2026-12-01  ·  16 min read  ·  tools

We listed every file link on 12 public pages, 964 of them, and asked for 458 of them politely. The servers were tidy: 456 of 458 HEAD answers were 200 with the usual type. The traps sat elsewhere: a page that redirects, a robots.txt that answers 403, wildcard rules that urllib.robotparser misreads, a HEAD that says 0 bytes, and PDFs of almost 70 MB.

You have a page that links to reports, data files or slides, and you want every file on your disk. That is two jobs: list the links that point to files, then fetch each one without saving an error page, half a file or two files under one name.

On 3 November 2026 we did both on 12 public pages: a public company's reports page, a central bank's meeting calendar, a standards body's code charts, an energy statistics agency's weekly report, a census bureau's file directory, a supreme court's opinions of one term, a labour statistics office's file archive, pages of two national statistics offices, a university course's lecture page, a tax agency's forms page and an open data portal's dataset page. A 13th page, the home page of another open data portal, is closed by its robots.txt, so we did not ask for it. We sent HEAD to every file link robots.txt left open, or to a random 80 where a page had more, and downloaded at most 5 files a page, cut off at 4 MiB: 458 HEAD requests and 57 downloads. We waited at least a second between requests to one host (the robots.txt fetch itself aside), longer where robots.txt sets a Crawl-delay: 547 requests in the main run. Apart from one robots.txt, nothing answered 403, nothing answered 429, and no host blocked us.

The short version#

  • 964 file links on 12 pages, from 2 to 370 a page: 667 PDF, 244 xlsx, 17 zip, 12 csv, 11 xls and 13 more (xml, json, txt and three map formats). 57 more links were the same link again on the same page.
  • The servers were tidy. 456 of the 458 HEAD answers were 200, none redirected, and each Content-Type was the usual one for its extension. All 57 downloads were, by their first bytes, what the extension said.
  • Resolve links against the address the page came from. The code charts page answered from another folder, over plain http. Against the address we asked for, all 370 of its links point elsewhere.
  • A robots.txt can answer 403. 26 of the 38 file links on the energy agency's page sit on a second host whose robots.txt did. We skipped them.
  • Python's urllib.robotparser does not read * and $. On 139 paths made to fit the wildcard rules in these robots.txt files, it gave the other answer on 138.
  • HEAD can be wrong about size. The open data portal's 8 file links all said Content-Length: 0 on HEAD. On GET, 4 of the 5 we fetched ran past 4 MiB.
  • Some files are big. 18 of the 25 lecture PDFs were over 4 MiB, the largest 69.9 MB.

The code#

Standard library only. file_links() reads the href and src of every tag, resolves them against the page's final address (or its <base>), drops the #part, percent-encodes spaces and non-ASCII letters, keeps each link once in page order, and keeps those whose path or query names a file type. download() streams one file to disk under a size cap and returns a row.

Every file link of a page, and one safe downloadpython
import email.message, hashlib, os, re, time, urllib.error, urllib.parse, urllib.request
from html.parser import HTMLParser

UA = "file-fetcher/1.0 (you@example.com)"
# what the first bytes of each kind of file are: zip covers docx, xlsx and pptx, ole the old .doc and .xls
KIND = {"pdf": "pdf", "docx": "zip", "xlsx": "zip", "pptx": "zip", "odt": "zip", "ods": "zip", "epub": "zip",
        "kmz": "zip", "zip": "zip", "doc": "ole", "xls": "ole", "ppt": "ole", "gz": "gzip", "7z": "7z", "rar": "rar",
        "csv": "text", "tsv": "text", "txt": "text", "json": "text", "xml": "text", "kml": "text",
        "geojson": "text", "rtf": "text"}
FILE_TYPES = set(KIND)
MAGIC = [(b"PK\x03\x04", "zip"), (b"\xd0\xcf\x11\xe0", "ole"), (b"\x1f\x8b", "gzip"), (b"7z\xbc\xaf", "7z"),
         (b"Rar!", "rar")]


# ---- the file links of a page
class _Links(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.base, self.values = None, []

    def handle_starttag(self, tag, attrs):
        for name, value in attrs:
            if tag == "base" and name == "href" and value and self.base is None:
                self.base = value.strip()
            elif name in ("href", "src") and value:
                self.values.append(value.strip())


def get_page(url):
    """(final url, html). Links are relative to the final url, so keep it."""
    wait(url)
    with _open(urllib.request.Request(url, headers={"User-Agent": UA}), timeout=30) as r:
        return r.geturl(), r.read().decode(r.headers.get_content_charset() or "utf-8", "replace")


def _pieces(url):
    """The path of a url and its query values: the file name can be in either (/file?uri=/a/b.xlsx)."""
    parts = urllib.parse.urlsplit(url)
    return [urllib.parse.unquote(parts.path)] + [v for _, v in urllib.parse.parse_qsl(parts.query)]


def _ext(piece):
    ext = os.path.splitext(piece.rstrip("/"))[1][1:].lower()
    return ext if ext in FILE_TYPES else ""


def extension(url):
    """The file type of a link, from its path or from a query value that names a file; '' if neither does."""
    return next((e for e in map(_ext, _pieces(url)) if e), "")


def file_links(page_url, html, types=FILE_TYPES):
    """Every href and src of a page that points to a file of `types`: absolute, without the #part, each once,
    in page order. page_url must be the url the page came from after redirects."""
    p = _Links()
    p.feed(html)
    base = urllib.parse.urljoin(page_url, p.base) if p.base else page_url
    found = {}
    for value in p.values:
        url = urllib.parse.urldefrag(urllib.parse.urljoin(base, value))[0]
        url = urllib.parse.quote(url, safe=":/?=&%@+,;~!$'()*")      # spaces and non-ASCII letters
        if url.startswith(("http://", "https://")) and extension(url) in types:
            found.setdefault(url, None)
    return list(found)


# ---- one file, safely
def sniff(head):
    """What the first bytes say a file is: pdf, zip, ole, gzip, 7z, rar, html or text."""
    if b"%PDF-" in head[:1024]:
        return "pdf"
    for magic, kind in MAGIC:
        if head.startswith(magic):
            return kind
    start = head[:1024].lstrip(b"\xef\xbb\xbf \t\r\n").lower()
    if start.startswith((b"<!doctype html", b"<html")) or b"<html" in start[:512]:
        return "html"
    return "binary" if b"\x00" in head[:1024] else "text"


def file_name(url, headers):
    """The name from Content-Disposition if the server sends one, else from the url, made safe for a disk."""
    msg = email.message.Message()
    msg["content-disposition"] = headers.get("Content-Disposition", "")
    name = msg.get_filename()
    if not name:
        pieces = _pieces(url)
        name = next((p for p in pieces if _ext(p)), pieces[0]).rstrip("/").rsplit("/", 1)[-1]
    name = name.replace("\\", "/").rsplit("/", 1)[-1]
    return re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", name).strip(". ")[:150] or "file"


def free_path(folder, name):
    """folder/name, or 'name (2).ext' and so on if that file is there already."""
    stem, ext = os.path.splitext(name)
    path, n = os.path.join(folder, name), 1
    while os.path.exists(path):
        n += 1
        path = os.path.join(folder, f"{stem} ({n}){ext}")
    return path


def download(url, folder, max_bytes=50 * 2**20):
    """Stream one file into folder. The file is kept only if it came whole and its first bytes are not a web page;
    the row says what happened either way."""
    row = {"url": url, "status": None, "final_url": None, "type": None, "length": None, "name": None,
           "named_by": None, "path": None, "bytes": 0, "sha256": None, "sniffed": None, "error": None}
    if not allowed(url):
        return {**row, "error": "robots.txt closes it"}
    wait(url)
    try:
        r = _open(urllib.request.Request(url, headers={"User-Agent": UA}), timeout=60)
    except urllib.error.HTTPError as e:          # 403, 404, 500 ...: nothing is written, so no error page as .pdf
        e.close()
        return {**row, "status": e.code, "error": f"HTTP {e.code}"}
    except (urllib.error.URLError, OSError) as e:
        return {**row, "error": str(getattr(e, "reason", e))}
    with r:
        row.update(status=r.status, final_url=r.geturl(), type=r.headers.get_content_type(),
                   length=r.headers.get("Content-Length"), name=file_name(url, r.headers),
                   named_by="Content-Disposition" if r.headers.get_filename() else "url")
        if row["length"] and int(row["length"]) > max_bytes:
            return {**row, "sniffed": sniff(r.read(2048)), "error": "larger than max_bytes"}
        os.makedirs(folder, exist_ok=True)
        part, digest, head = free_path(folder, row["name"] + ".part"), hashlib.sha256(), b""
        try:
            with open(part, "wb") as f:
                while chunk := r.read(1 << 16):
                    head = head or chunk[:2048]
                    row["bytes"] += len(chunk)
                    if row["bytes"] > max_bytes:
                        break
                    digest.update(chunk)
                    f.write(chunk)
        except OSError as e:                     # a timeout or a dropped connection halfway through
            os.remove(part)
            return {**row, "error": f"broke off: {e}"}
    row["sniffed"] = sniff(head)
    if row["bytes"] > max_bytes:
        row["error"] = "larger than max_bytes"
    elif row["length"] and row["bytes"] != int(row["length"]):
        row["error"] = "cut short"
    elif row["sniffed"] == "html":
        row["error"] = "a web page, not the file"
    if row["error"]:
        os.remove(part)
        return row
    row["path"], row["sha256"] = free_path(folder, row["name"]), digest.hexdigest()
    os.replace(part, row["path"])
    return row

The robots.txt part and the pause between requests go in the same file:

robots.txt, the longest matching rule wins, and a pause per hostpython
# robots.txt read as RFC 9309 says: the longest matching rule wins, * and $ work
_robots, _last = {}, {}


def robots_txt(origin):
    """The text of origin/robots.txt: '' if there is none (404 and most 4xx), None if it closes the host to us
    (401, 403, 5xx or no answer)."""
    try:
        req = urllib.request.Request(origin + "/robots.txt", headers={"User-Agent": UA})
        return urllib.request.urlopen(req, timeout=30).read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return "" if 400 <= e.code < 500 and e.code not in (401, 403) else None
    except (urllib.error.URLError, OSError):
        return None


def parse_robots(text, agent=UA.split("/")[0].lower()):
    """(rules, crawl delay) of the groups that name our agent, or of the * groups if none does."""
    groups, group, naming = [], None, False
    for line in re.split(r"\r\n|\r|\n", text):
        line = line.split("#", 1)[0]
        if ":" not in line:
            continue
        field, value = (s.strip() for s in line.split(":", 1))
        field = field.lower()
        if field == "user-agent":
            if not naming:
                group = {"agents": [], "rules": [], "delay": 0}
                groups.append(group)
            group["agents"].append(value.lower())
            naming = True
        elif field in ("allow", "disallow") and group:
            if value:
                anchored = value.endswith("$")
                rx = re.escape(value.rstrip("$") if anchored else value).replace(r"\*", ".*")
                group["rules"].append((field == "allow", re.compile(rx + ("$" if anchored else "")), len(value)))
            naming = False
        elif field != "sitemap":
            if field == "crawl-delay" and group and re.fullmatch(r"\d+(\.\d+)?", value):
                group["delay"] = float(value)
            naming = False
    mine = [g for g in groups if agent in g["agents"]] or [g for g in groups if "*" in g["agents"]]
    return [r for g in mine for r in g["rules"]], max([g["delay"] for g in mine] or [0])


def robots(url):
    """(rules, crawl delay) for the host of url; rules is None when its robots.txt closes it."""
    origin = "{0.scheme}://{0.netloc}".format(urllib.parse.urlsplit(url))
    if origin not in _robots:
        text = robots_txt(origin)
        _robots[origin] = (None, 0) if text is None else parse_robots(text)
        _last[urllib.parse.urlsplit(url).netloc] = time.monotonic()
    return _robots[origin]


def allowed(url):
    """May we fetch url? The longest rule that matches its path wins; on a tie, Allow wins."""
    rules = robots(url)[0]
    if rules is None:
        return False
    path = re.sub(r"^[a-zA-Z][a-zA-Z0-9+.-]*://[^/?#]*", "", url).split("#", 1)[0]
    path = path if path.startswith("/") else "/" + path
    best = None
    for allow, rx, length in rules:
        if rx.match(path) and (best is None or length > best[1] or (length == best[1] and allow)):
            best = (allow, length)
    return best is None or best[0]


def wait(url, pause=1.0):
    """Sleep so that requests to one host are `pause` seconds apart, or Crawl-delay if robots.txt asks for more."""
    host = urllib.parse.urlsplit(url).netloc
    time.sleep(max(0, _last.get(host, 0) + max(pause, robots(url)[1]) - time.monotonic()))
    _last[host] = time.monotonic()


class _Hops(urllib.request.HTTPRedirectHandler):
    """Follow a redirect only where robots.txt allows it, and only after the same pause."""
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        if not allowed(newurl):
            raise urllib.error.URLError("robots.txt closes " + newurl)
        wait(newurl)
        return super().redirect_request(req, fp, code, msg, headers, newurl)


_open = urllib.request.build_opener(_Hops).open
Run itpython
page, html = get_page("https://www2.census.gov/programs-surveys/popest/technical-documentation/"
                      "file-layouts/2020-2024/")
links = file_links(page, html)
print(len(links), "file links, the first:", links[0])
for url in links[:3]:
    row = download(url, "file-layouts", max_bytes=20 * 2**20)
    print(row["status"], row["path"], row["bytes"], row["sniffed"], row["error"])

It printed 26 file links in that directory, the first CBSA-EST2024-AGESEX.pdf, and three rows: status 200, the path in file-layouts, 102,602, 81,711 and 89,236 bytes, pdf by the first bytes, no error.

The traps, one by one#

  1. Resolve links against the final address. We asked the standards body for its /charts/ page over https; the page came from /Public/18.0.0/charts/, over plain http. Resolved against the address we asked for, all 370 of its file links point elsewhere: PDF/U08A0.pdf lands in /charts/PDF/ instead of /Public/18.0.0/charts/PDF/. Here the server catches the mistake: the three we tried took a 301 and a 302 each to reach the same file, three requests instead of one. get_page() returns the final address for that reason. The same three files also answered 200 over https with the same size and date, so you can put the https back.
  2. Count a link once. 57 of the 1,021 file links were a link the same page had already given, 49 of them on the code charts page. file_links() keeps the first.
  3. The file type is not always in the path. The second statistics office links its two spreadsheets as /file?uri= followed by the file's path, such as /file?uri=/.../name.xlsx. A filter on the path's extension finds neither, and a name taken from the path calls both file. extension() and file_name() also read the query. The server's Content-Disposition, sent on those 2 of the 456 answers and on no other, gave the same names.
  4. A type filter also catches parts of the page. Of the 13 links that were not PDF, spreadsheet, zip or csv, 3 have the names of page parts, not documents: filelist.xml and colorschememapping.xml in the reports page's own reports_files folder, and the labour statistics office's manifest.json. Pass types={"pdf"} to file_links() when you want PDFs only.
  5. A 404 comes with a page of its own. Those two XML files answered 404 with a 355-byte HTML page. Code that writes whatever comes back saves that page under the file's name. urlopen raises on a 404, so download() writes nothing, and it also throws away a 200 whose first bytes are HTML. That second check never fired here: the 57 downloads were 40 PDF, 12 zip-based files (xlsx, zip, kmz), 1 old xls and 4 text files (xml, kml, geojson), each matching its extension.
  6. Check robots.txt per host and per redirect. File links can sit on another host than the page. On the energy agency's weekly report, 26 of the 38 were on a second host whose robots.txt answered 403. We read 401 and 403 as closed, which is also what urllib.robotparser did when we pointed it at that host, and skipped all 26. Of the 16 robots.txt files we asked for (one per host and scheme), 12 answered 200, 3 answered 404, which means no rules, and 1 answered 403. None of the 964 links was closed by a Disallow line. download() checks the link, and _Hops checks every redirect target before following it.
  7. Read * and $ the standard way. 6 of those robots.txt files had rules with * or $, 139 in all. urllib.robotparser compares them as plain text: on 139 paths made to fit those rules, it gave the other answer on 138. On the 979 real addresses the run checked it gave the same answer every time; the gap shows only on paths the wildcard rules are written for. On those paths it opened search pages the tax agency closes and archive folders the energy agency closes, and it closed the style sheets, scripts and images that three of the sites open. Our robots code lets the longest matching rule win; it agreed with our reference reader on all 979 addresses the run checked, and on those 139 paths.
  8. Do not trust HEAD for the size. The portal's 8 file links said Content-Length: 0 on HEAD. On GET none of the 5 we fetched sent a length; 4 ran past the 4 MiB cap and the fifth was 7,233 bytes. Across all pages, 5 of 456 HEAD answers and 8 of 57 downloads came with no length at all. So download() counts the bytes as they come and stops at max_bytes, and where a length was sent it compares: they matched on all 49 files kept with one.
  9. Cap the size. The course's 25 lecture PDFs had a median of 7.2 MB, and 18 were over 4 MiB; the largest was 69.9 MB. The largest of the 80 code charts we asked about was 42.6 MB. max_bytes defaults to 50 MiB; set it for your job.
  10. Names and doubles. download() names a file from Content-Disposition when the server sends one, else from the address, takes out characters a disk does not accept, and writes name (2).pdf rather than overwrite. Among the 456 HEAD answers, no two had the same size and the same ETag or Last-Modified, and no two of the 53 files we kept (the 57 downloads less the 4 that ran past the cap) had the same SHA-256. The row keeps the hash so you can check on your own pages.

Many pages at once#

For many pages, or on a schedule, our Bulk File Downloader on Apify does the fetching. Give it web pages or direct file links, and pick the types: PDF, documents, archives, images, video or audio. File types defaults to images only and Maximum files per page to 200. Formats outside those groups, such as XML, JSON, KML and GeoJSON, are not taken from pages: give them as direct file links. Each file is stored with a link you can open, plus its name, type, size and SHA-256 checksum, and for images the width, height and alt text; images come in the largest size the page offers. The same file under two links is stored once and not charged, and files are read only where robots.txt allows it. It reads robots.txt per host: an answer in the 4xx range counts as no rules, unless the answer is an anti-bot page, and a 5xx or no answer counts as closed. That is looser than the code above, which read a 401 or 403 as closed and skipped that host. The actor also skips files on a host whose robots.txt closes them to named machine learning agents. Pages are read as HTML without a browser, so files a page shows only after running JavaScript are not found. It is billed per file stored: a file up to 10 MB counts once, and a larger one counts once more for each started 10 MB, so the 69.9 MB PDF above would count 7 times. How to set it up, step by step: Bulk file download.

written