#!/usr/bin/env python3 """Find all pages of a website with the Ujeebu Crawl API. 1. Extract every URL from the site's sitemaps (sitemap mode: no page is read, 0 credits). 2. Quote a crawl that follows the links of one section (free), then run it capped at the quote. 3. Compare the two lists: orphans (in the sitemap, reached by no link) and pages missing from the sitemap (linked and live). Everything goes to all-pages.csv. pip install requests UJEEBU_API_KEY=your-key python3 find_all_pages.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" SITE = "https://ujeebu.com/" SECTION = "/blog" # the part of the site to crawl link by link 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): """Poll the job until it has finished (every page ended, archive built).""" while True: job = api("GET", f"/crawl/{job_id}") if job["finished"]: return job time.sleep(5) def page_records(job_id): """Every page record of a finished job, 50 at a time, following the cursor.""" 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 clean(url): """One spelling per URL: no fragment, no trailing slash (except on the root).""" url = url.split("#")[0] return url if urlparse(url).path in ("", "/") else url.rstrip("/") def in_section(url): path = urlparse(url).path.rstrip("/") return path == SECTION or path.startswith(SECTION + "/") # 1. Every URL in the sitemaps, for 0 credits. listing = api("POST", "/crawl", json={"urls": [SITE], "mode": "sitemap", "scope": {"max_pages": 1000}}) listing = wait(listing["job_id"]) sitemap = {clean(p["url"]) for p in page_records(listing["job_id"])} sections = collections.Counter("/" + urlparse(u).path.strip("/").split("/")[0] for u in sitemap) print(f"Sitemap: {len(sitemap)} URLs, {listing['credits_used']} credits") for section, count in sections.most_common(6): print(f" {section:<12}{count:>5}") # 2. Follow the links of one section. The quote gives the most it can cost; the cap holds it there. crawl = { "urls": [SITE.rstrip("/") + SECTION], "scope": { "include": [SECTION + "/**"], "exclude": [SECTION + "?*", SECTION + "/**?*"], # ?tag= and ?author= views: copies of the list pages "max_depth": 5, "max_pages": 200, }, "use_sitemap": False, # links only, so the comparison with the sitemap means something "format": "html", "page": {"js": False}, # plain HTML: the cheapest page, and every is counted } quote = api("POST", "/crawl/quote", json=crawl) print(f"Quote: {quote['credits_per_page']} credit a page, at most {quote['credits_ceiling']} credits") job = api("POST", "/crawl", json={**crawl, "max_credits": quote["credits_ceiling"]}) job = wait(job["job_id"]) crawled = {clean(p["url"]): p for p in page_records(job["job_id"])} print(f"Link crawl: {job['counts']['done']} pages read, {job['credits_used']} credits, " f"stop_reason={job['stop_reason']}") # 3. Compare the two lists. listed = {u for u in sitemap if in_section(u)} found = {u for u, p in crawled.items() if p["state"] == "done"} orphans = sorted(listed - set(crawled)) # in the sitemap, reached by no link unlisted = sorted(found - listed) # linked and live, missing from the sitemap with open("all-pages.csv", "w", newline="") as f: out = csv.writer(f) out.writerow(["url", "in_sitemap", "found_by_links", "state", "http_status", "title"]) for url in sorted(listed | set(crawled)): page = crawled.get(url, {}) out.writerow([url, url in listed, url in crawled, page.get("state", ""), page.get("http_status", ""), page.get("title", "")]) print(f"{SECTION}: {len(listed)} in the sitemap, {len(found)} found by links, {len(listed & found)} in both") print(f" {len(orphans)} orphans (in the sitemap, no link to them)") for url in orphans[:5]: print(f" {url}") print(f" {len(unlisted)} pages missing from the sitemap") for url in unlisted[:5]: print(f" {url}")