#!/usr/bin/env python3 """Fetch URLs under a plain client name and save each with a log line (UTC time, status, bytes, SHA-256). python3 -I fetch_save.py = [= ...] Each file is written to /; a line is appended to /FETCHLOG.tsv: time_utc, name, final_url, http_status, bytes, sha256, requested_url. Nothing is retried past a refusal: a 403/429 or a bot-check page is logged and left for a person. """ import datetime as dt import hashlib import sys import urllib.error import urllib.request from pathlib import Path UA = "factchecked-research/1.0" def fetch(url, timeout=60): req = urllib.request.Request(url, headers={"User-Agent": UA}) try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, r.geturl(), r.read() except urllib.error.HTTPError as e: return e.code, url, e.read() if hasattr(e, "read") else b"" def main(): out = Path(sys.argv[1]) out.mkdir(parents=True, exist_ok=True) log = out / "FETCHLOG.tsv" new = not log.exists() with log.open("a", encoding="utf-8", newline="\n") as fh: if new: fh.write("time_utc\tname\tfinal_url\thttp_status\tbytes\tsha256\trequested_url\n") for arg in sys.argv[2:]: name, url = arg.split("=", 1) t = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") try: status, final, body = fetch(url) except Exception as e: # network error: log it, keep going fh.write(f"{t}\t{name}\t-\tERR {type(e).__name__}: {e}\t0\t-\t{url}\n") print(f"{name}: ERROR {e}") continue (out / name).write_bytes(body) h = hashlib.sha256(body).hexdigest() fh.write(f"{t}\t{name}\t{final}\t{status}\t{len(body)}\t{h}\t{url}\n") print(f"{name}: {status} {len(body)} bytes sha256 {h[:16]}… {final}") if __name__ == "__main__": main()