#!/usr/bin/env python3 """Crawl a site through a Crawl4AI server and save each page as Markdown. python3 crawl.py URL [MAX_PAGES] [MAX_DEPTH] Pages go to ~/crawls//, one .md file per page, with index.jsonl listing URL, title, status code, depth and file. Only Python's standard library is used. Environment: CRAWL4AI_URL the server (default http://localhost:8000) CRAWL4AI_API_TOKEN its token (default: read from ~/crawl4ai/.env if it exists; none for a VM-to-VM integration, which adds it) EXE_VM_TOKEN an exe.dev VM token, sent as X-Exedev-Authorization, when the server is reached through https://.exe.xyz CRAWLS_DIR where to save (default ~/crawls) """ import json, os, re, sys, time, urllib.request from pathlib import Path from urllib.parse import urlparse if len(sys.argv) < 2: sys.exit(__doc__) start = sys.argv[1] max_pages = int(sys.argv[2]) if len(sys.argv) > 2 else 50 max_depth = int(sys.argv[3]) if len(sys.argv) > 3 else 2 server = os.environ.get("CRAWL4AI_URL", "http://localhost:8000").rstrip("/") token = os.environ.get("CRAWL4AI_API_TOKEN") env = Path.home() / "crawl4ai" / ".env" if not token and env.exists(): for line in env.read_text().splitlines(): if line.startswith("CRAWL4AI_API_TOKEN="): token = line.split("=", 1)[1].strip() headers = {"Content-Type": "application/json"} if token: headers["Authorization"] = f"Bearer {token}" if os.environ.get("EXE_VM_TOKEN"): headers["X-Exedev-Authorization"] = f"Bearer {os.environ['EXE_VM_TOKEN']}" # A breadth-first crawl that stays on the start URL's site, skips what # robots.txt disallows, and never reads the server's cache. body = { "urls": [start], "crawler_config": {"type": "CrawlerRunConfig", "params": { "cache_mode": "bypass", "check_robots_txt": True, "deep_crawl_strategy": {"type": "BFSDeepCrawlStrategy", "params": { "max_depth": max_depth, "max_pages": max_pages}}, }}, } t0 = time.time() req = urllib.request.Request(server + "/crawl", data=json.dumps(body).encode(), headers=headers) try: with urllib.request.urlopen(req, timeout=330) as r: data = json.load(r) except urllib.error.HTTPError as e: sys.exit(f"crawl failed: HTTP {e.code}: {e.read().decode()[:300]}") out = Path(os.environ.get("CRAWLS_DIR", Path.home() / "crawls")) / urlparse(start).netloc out.mkdir(parents=True, exist_ok=True) saved = 0 with open(out / "index.jsonl", "w") as index: for page in data.get("results", []): u = urlparse(page["url"]) name = re.sub(r"[^A-Za-z0-9._-]+", "_", (u.path + ("_" + u.query if u.query else "")).strip("/")) or "index" md = (page.get("markdown") or {}).get("raw_markdown") or "" meta = page.get("metadata") or {} rec = {"url": page["url"], "title": meta.get("title"), "status": page.get("status_code"), "depth": meta.get("depth"), "success": page.get("success")} if page.get("success") and md: (out / f"{name}.md").write_text(md) rec["file"] = f"{name}.md" saved += 1 index.write(json.dumps(rec) + "\n") print(f"{saved} pages saved to {out} in {time.time() - t0:.0f} s")