#!/usr/bin/env python3 """Build a website content inventory before a migration, with the Ujeebu Crawl API. Crawls the site as HTML without JavaScript (the cheapest format), then writes: inventory.csv the content inventory: one row per URL with status, title, canonical, depth, links in and out, plus empty action and notes columns for the audit broken-links.csv URLs that answer 404 or 410, with the pages that link to them redirects.csv a first redirect map: each page and its URL on the new site pip install requests UJEEBU_API_KEY=your-key python3 site_inventory.py """ import collections import csv import os import time from urllib.parse import urlparse import requests API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY") API = "https://api.ujeebu.com" CRAWL = { "urls": ["https://ujeebu.com/"], "scope": {"max_depth": 2, "max_pages": 100}, "format": "html", "page": {"js": False}, # plain HTML: the cheapest page "max_credits": 150, "concurrency": 3, } NEW_SITE = "https://new.example.com" # where the site is moving MOVES = [ # old path prefix -> new path prefix, first match wins ("/blog/", "/resources/blog/"), ("/docs/", "/developers/docs/"), ] http = requests.Session() http.headers["ApiKey"] = API_KEY def api(method, path, **kwargs): """Call the Crawl API. A GET is tried again after a network error: polling runs for minutes.""" for attempt in range(1, 4): try: response = http.request(method, API + path, timeout=60, **kwargs) break except requests.ConnectionError: if method != "GET" or attempt == 3: raise time.sleep(5 * attempt) if response.status_code >= 400: raise SystemExit(f"{method} {path}: {response.status_code} {response.text}") return response.json() def wait(job_id): while True: job = api("GET", f"/crawl/{job_id}") if job["finished"]: return job print(f" {job['status']}: {job['counts']['done']} done, {job['counts']['pending']} pending") time.sleep(10) def page_records(job_id): after = 0 while True: batch = api("GET", f"/crawl/{job_id}/pages", params={"after": after, "limit": 50}) yield from batch["pages"] if not batch["has_more"]: return after = batch["next_after"] def new_url(url): """The page's URL on the new site: same path, unless a MOVES rule applies.""" path = urlparse(url).path or "/" for old, new in MOVES: old, new = old.rstrip("/"), new.rstrip("/") if path == old or path.startswith(old + "/"): return NEW_SITE + new + path[len(old):] return NEW_SITE + path def keeper(page): """The URL that stays for this page's document: the canonical URL, else the page itself.""" if page.get("duplicate_of") in by_url: page = by_url[page["duplicate_of"]] return page.get("canonical_url") or page["url"] job = api("POST", "/crawl", json=CRAWL) print(f"Started {job['job_id']}") job = wait(job["job_id"]) pages = list(page_records(job["job_id"])) by_url = {p["url"]: p for p in pages} # Who links to whom: links are absolute URLs, one list per page (up to 300, links_total says how many). linked_from = collections.defaultdict(set) for page in pages: for link in page.get("links") or []: linked_from[link.split("#")[0]].add(page["url"]) with open("inventory.csv", "w", newline="") as f: out = csv.writer(f) out.writerow(["url", "state", "http_status", "error_class", "title", "canonical_url", "duplicate_of", "depth", "links_out", "links_in", "action", "notes"]) for p in pages: out.writerow([p["url"], p["state"], p.get("http_status", ""), p.get("error_class") or "", p.get("title", ""), p.get("canonical_url", ""), p.get("duplicate_of", ""), p["depth"], p.get("links_total", 0), len(linked_from[p["url"]]), "", ""]) broken = [p for p in pages if p.get("error_class") == "not_found"] with open("broken-links.csv", "w", newline="") as f: out = csv.writer(f) out.writerow(["broken_url", "http_status", "linked_from"]) for p in broken: out.writerow([p["url"], p.get("http_status", ""), " ".join(sorted(linked_from[p["url"]]))]) with open("redirects.csv", "w", newline="") as f: out = csv.writer(f) out.writerow(["old_url", "new_url", "note"]) for p in pages: if p["state"] == "done" or p.get("error_class") == "duplicate": keep = keeper(p) out.writerow([p["url"], new_url(keep), f"same document as {keep}" if keep != p["url"] else ""]) states = collections.Counter(p.get("error_class") or p["state"] for p in pages) print(f"{len(pages)} URLs: {dict(states)}; {job['credits_used']} credits ({job['stop_reason']})") print(f"{len(broken)} broken URLs") for p in broken[:10]: print(f" {p['url']} ({p.get('http_status')}), linked from {len(linked_from[p['url']])} pages")