#!/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 <a href> 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}")
#!/usr/bin/env node
/**
* 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.
*
* UJEEBU_API_KEY=your-key node find-all-pages.js (Node.js 18 or later, no dependencies)
*/
const fs = require('fs');
const API_KEY = process.env.UJEEBU_API_KEY || 'YOUR_API_KEY';
const API = 'https://api.ujeebu.com';
const SITE = 'https://ujeebu.com/';
const SECTION = '/blog'; // the part of the site to crawl link by link
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Call the Crawl API. A GET is tried again after a network error: polling runs for minutes. */
async function api(method, path, body) {
for (let attempt = 1; ; attempt += 1) {
let response;
try {
response = await fetch(API + path, {
method,
headers: { ApiKey: API_KEY, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (err) {
if (method !== 'GET' || attempt === 3) throw err;
await sleep(5000 * attempt);
continue;
}
if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${await response.text()}`);
return response.json();
}
}
/** Poll the job until it has finished (every page ended, archive built). */
async function wait(jobId) {
for (;;) {
const job = await api('GET', `/crawl/${jobId}`);
if (job.finished) return job;
await sleep(5000);
}
}
/** Every page record of a finished job, 50 at a time, following the cursor. */
async function pageRecords(jobId) {
const pages = [];
for (let after = 0; ;) {
const batch = await api('GET', `/crawl/${jobId}/pages?after=${after}&limit=50`);
pages.push(...batch.pages);
if (!batch.has_more) return pages;
after = batch.next_after;
}
}
/** One spelling per URL: no fragment, no trailing slash (except on the root). */
function clean(url) {
const u = url.split('#')[0];
return ['', '/'].includes(new URL(u).pathname) ? u : u.replace(/\/+$/, '');
}
function inSection(url) {
const path = new URL(url).pathname.replace(/\/+$/, '');
return path === SECTION || path.startsWith(SECTION + '/');
}
const csvCell = (v) => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
async function main() {
// 1. Every URL in the sitemaps, for 0 credits.
let listing = await api('POST', '/crawl', { urls: [SITE], mode: 'sitemap', scope: { max_pages: 1000 } });
listing = await wait(listing.job_id);
const sitemap = new Set((await pageRecords(listing.job_id)).map((p) => clean(p.url)));
const sections = new Map();
for (const url of sitemap) {
const first = '/' + new URL(url).pathname.replace(/^\/+|\/+$/g, '').split('/')[0];
sections.set(first, (sections.get(first) || 0) + 1);
}
console.log(`Sitemap: ${sitemap.size} URLs, ${listing.credits_used} credits`);
[...sections].sort((a, b) => b[1] - a[1]).slice(0, 6)
.forEach(([section, count]) => console.log(` ${section.padEnd(12)}${String(count).padStart(5)}`));
// 2. Follow the links of one section. The quote gives the most it can cost; the cap holds it there.
const crawl = {
urls: [SITE.replace(/\/$/, '') + 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 <a href> is counted
};
const quote = await api('POST', '/crawl/quote', crawl);
console.log(`Quote: ${quote.credits_per_page} credit a page, at most ${quote.credits_ceiling} credits`);
let job = await api('POST', '/crawl', { ...crawl, max_credits: quote.credits_ceiling });
job = await wait(job.job_id);
const crawled = new Map((await pageRecords(job.job_id)).map((p) => [clean(p.url), p]));
console.log(`Link crawl: ${job.counts.done} pages read, ${job.credits_used} credits, stop_reason=${job.stop_reason}`);
// 3. Compare the two lists.
const listed = new Set([...sitemap].filter(inSection));
const found = new Set([...crawled].filter(([, p]) => p.state === 'done').map(([url]) => url));
const orphans = [...listed].filter((url) => !crawled.has(url)).sort(); // in the sitemap, reached by no link
const unlisted = [...found].filter((url) => !listed.has(url)).sort(); // linked and live, missing from the sitemap
const rows = [['url', 'in_sitemap', 'found_by_links', 'state', 'http_status', 'title']];
for (const url of [...new Set([...listed, ...crawled.keys()])].sort()) {
const page = crawled.get(url) || {};
rows.push([url, listed.has(url) ? 'True' : 'False', crawled.has(url) ? 'True' : 'False',
page.state || '', page.http_status ?? '', page.title || '']);
}
fs.writeFileSync('all-pages.csv', rows.map((r) => r.map(csvCell).join(',')).join('\n') + '\n');
const both = [...listed].filter((url) => found.has(url)).length;
console.log(`${SECTION}: ${listed.size} in the sitemap, ${found.size} found by links, ${both} in both`);
console.log(` ${orphans.length} orphans (in the sitemap, no link to them)`);
orphans.slice(0, 5).forEach((url) => console.log(` ${url}`));
console.log(` ${unlisted.length} pages missing from the sitemap`);
unlisted.slice(0, 5).forEach((url) => console.log(` ${url}`));
}
main().catch((err) => { console.error(err.message); process.exit(1); });