#!/usr/bin/env python3 """The same crawl as one Ujeebu Crawl API job: get the quote, cap the job at it, read the page records. The API reads every page through the Ujeebu API (proxies, block handling, JavaScript when you ask for it), honours robots.txt, spots duplicates by their canonical URL and stops at max_credits. Writes pages.csv like the do-it-yourself crawler. pip install requests UJEEBU_API_KEY=your-key python3 crawl_with_api.py """ import csv import os import time import requests API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY") API = "https://api.ujeebu.com" CRAWL = { "urls": ["https://books.toscrape.com/"], "scope": {"max_pages": 50}, "format": "html", "page": {"js": False}, # set True for sites that render with JavaScript } http = requests.Session() http.headers["ApiKey"] = API_KEY def api(method, path, **kwargs): response = http.request(method, API + path, timeout=60, **kwargs) if response.status_code >= 400: raise SystemExit(f"{method} {path}: {response.status_code} {response.text}") return response.json() started = time.time() 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"]}) while not job.get("finished"): time.sleep(5) job = api("GET", f"/crawl/{job['job_id']}") rows, after = [], 0 while True: batch = api("GET", f"/crawl/{job['job_id']}/pages", params={"after": after, "limit": 50}) rows += [[p["url"], p.get("http_status") or p.get("error_class"), p.get("title", "")] for p in batch["pages"]] if not batch["has_more"]: break after = batch["next_after"] with open("pages.csv", "w", newline="") as f: csv.writer(f).writerows([["url", "status", "title"], *rows]) print(f"{len(rows)} pages in {time.time() - started:.0f} s: {dict(job['counts'])}") print(f"stop_reason={job['stop_reason']}, {job['credits_used']} credits, robots.txt: {job['robots'][0]['status']}")