Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.
Python aiai-agentscrawl4ai-cloudcrawlerdata-extractionllmmarkdownmcpopen-sourceplaywrightpythonragscraperweb-crawlerweb-crawlingweb-scraping
feat: Add DomainMapper for comprehensive domain URL discovery
unclecode9d5bcf78e293
diff --git a/crawl4ai/__init__.py b/crawl4ai/__init__.pyindex 00e75f98..0d1071ae 100644--- a/crawl4ai/__init__.py+++ b/crawl4ai/__init__.py@@ -3,7 +3,7 @@ import warningsfrom .async_webcrawler import AsyncWebCrawler, CacheMode# MODIFIED: Add SeedingConfig and VirtualScrollConfig here-from .async_configs import BrowserConfig, CrawlerRunConfig, HTTPCrawlerConfig, LLMConfig, ProxyConfig, GeolocationConfig, SeedingConfig, VirtualScrollConfig, LinkPreviewConfig, MatchMode+from .async_configs import BrowserConfig, CrawlerRunConfig, HTTPCrawlerConfig, LLMConfig, ProxyConfig, GeolocationConfig, SeedingConfig, VirtualScrollConfig, LinkPreviewConfig, MatchMode, DomainMapperConfigfrom .content_scraping_strategy import (ContentScrapingStrategy,@@ -78,6 +78,7 @@ from .deep_crawling import ()# NEW: Import AsyncUrlSeederfrom .async_url_seeder import AsyncUrlSeeder+from .domain_mapper import DomainMapper# Adaptive Crawlerfrom .adaptive_crawler import (AdaptiveCrawler,@@ -122,6 +123,9 @@ __all__ = ["VirtualScrollConfig",# NEW: Add AsyncUrlSeeder"AsyncUrlSeeder",+ # DomainMapper+ "DomainMapper",+ "DomainMapperConfig",# Adaptive Crawler"AdaptiveCrawler","AdaptiveConfig",diff --git a/crawl4ai/async_configs.py b/crawl4ai/async_configs.pyindex f7544866..1037ebc4 100644--- a/crawl4ai/async_configs.py+++ b/crawl4ai/async_configs.py@@ -126,7 +126,7 @@ ALLOWED_DESERIALIZE_TYPES = {# Config classes"BrowserConfig", "CrawlerRunConfig", "HTTPCrawlerConfig","LLMConfig", "ProxyConfig", "GeolocationConfig",- "SeedingConfig", "VirtualScrollConfig", "LinkPreviewConfig",+ "SeedingConfig", "VirtualScrollConfig", "LinkPreviewConfig", "DomainMapperConfig",# Extraction strategies"JsonCssExtractionStrategy", "JsonXPathExtractionStrategy","JsonLxmlExtractionStrategy", "LLMExtractionStrategy",@@ -2211,3 +2211,89 @@ class SeedingConfig:config_dict = self.to_dict()config_dict.update(kwargs)return SeedingConfig.from_kwargs(config_dict)+++class DomainMapperConfig:+ """+ Configuration for comprehensive domain URL discovery via DomainMapper.++ Discovers all URLs under a domain using multiple sources (sitemap, Common Crawl,+ Wayback Machine, Certificate Transparency, path probing, robots.txt mining,+ RSS/Atom feeds, homepage link extraction) without deep crawling.+ """+ def __init__(+ self,+ source: str = "sitemap+cc+crt+probe",+ max_urls: int = -1,+ concurrency: int = 50,+ hits_per_sec: int = 10,+ force: bool = False,+ extract_head: bool = True,+ filter_nonsense_urls: bool = True,+ soft_404_detection: bool = True,+ query: Optional[str] = None,+ score_threshold: Optional[float] = None,+ scoring_method: str = "bm25",+ probe_paths: Optional[List[str]] = None,+ common_subdomains: Optional[List[str]] = None,+ use_browser_for_homepage: bool = False,+ verbose: Optional[bool] = None,+ cache_ttl_hours: int = 24,+ base_directory: Optional[str] = None,+ dns_timeout: float = 3.0,+ http_timeout: float = 10.0,+ ):+ """+ Args:+ source: Discovery sources joined by '+'. Valid: sitemap, cc, wayback,+ crt, probe, robots, feed, homepage. Default: "sitemap+cc+crt+probe"+ max_urls: Maximum URLs to return. -1 for unlimited.+ concurrency: Max concurrent requests across all hosts.+ hits_per_sec: Rate limit in requests/second.+ force: Bypass all caches.+ extract_head: Fetch and parse <head> metadata for each URL.+ filter_nonsense_urls: Filter utility URLs (robots.txt, favicon, etc.).+ soft_404_detection: Fingerprint and filter soft-404 pages (SPAs).+ query: BM25 relevance query. Requires extract_head=True.+ score_threshold: Minimum relevance score (0.0-1.0) to include URL.+ scoring_method: Scoring algorithm. Currently only "bm25".+ probe_paths: Extra paths to probe on each host (added to defaults).+ common_subdomains: Extra subdomain prefixes to guess (added to defaults).+ use_browser_for_homepage: Use Playwright for JS-rendered homepages.+ verbose: Override logger verbose setting.+ cache_ttl_hours: Hours before cached results expire.+ base_directory: Base directory for cache files.+ dns_timeout: Timeout in seconds for DNS resolution.+ http_timeout: Timeout in seconds for HTTP requests.+ """+ self.source = source+ self.max_urls = max_urls+ self.concurrency = concurrency+ self.hits_per_sec = hits_per_sec+ self.force = force+ self.extract_head = extract_head+ self.filter_nonsense_urls = filter_nonsense_urls+ self.soft_404_detection = soft_404_detection+ self.query = query+ self.score_threshold = score_threshold+ self.scoring_method = scoring_method+ self.probe_paths = probe_paths+ self.common_subdomains = common_subdomains+ self.use_browser_for_homepage = use_browser_for_homepage+ self.verbose = verbose+ self.cache_ttl_hours = cache_ttl_hours+ self.base_directory = base_directory+ self.dns_timeout = dns_timeout+ self.http_timeout = http_timeout++ def to_dict(self) -> Dict[str, Any]:+ return {k: v for k, v in self.__dict__.items()}++ @staticmethod+ def from_kwargs(kwargs: Dict[str, Any]) -> 'DomainMapperConfig':+ return DomainMapperConfig(**kwargs)++ def clone(self, **kwargs: Any) -> 'DomainMapperConfig':+ config_dict = self.to_dict()+ config_dict.update(kwargs)+ return DomainMapperConfig.from_kwargs(config_dict)diff --git a/crawl4ai/async_webcrawler.py b/crawl4ai/async_webcrawler.pyindex f81096c0..e6f2c85f 100644--- a/crawl4ai/async_webcrawler.py+++ b/crawl4ai/async_webcrawler.py@@ -36,10 +36,11 @@ from .markdown_generation_strategy import ()from .deep_crawling import DeepCrawlDecoratorfrom .async_logger import AsyncLogger, AsyncLoggerBase-from .async_configs import BrowserConfig, CrawlerRunConfig, ProxyConfig, SeedingConfig+from .async_configs import BrowserConfig, CrawlerRunConfig, ProxyConfig, SeedingConfig, DomainMapperConfigfrom .async_dispatcher import * # noqa: F403from .async_dispatcher import BaseDispatcher, MemoryAdaptiveDispatcher, RateLimiterfrom .async_url_seeder import AsyncUrlSeeder+from .domain_mapper import DomainMapperfrom .utils import (sanitize_input_encode,@@ -170,6 +171,7 @@ class AsyncWebCrawler:self.arun = self._deep_handler(self.arun)self.url_seeder: Optional[AsyncUrlSeeder] = None+ self._domain_mapper: Optional[DomainMapper] = Noneasync def start(self):"""@@ -1198,4 +1200,36 @@ class AsyncWebCrawler:seeding_config)else:- raise ValueError("`domain_or_domains` must be a string or a list of strings.")\ No newline at end of file+ raise ValueError("`domain_or_domains` must be a string or a list of strings.")++ async def amap_domain(+ self,+ domain: str,+ config: Optional[DomainMapperConfig] = None,+ **kwargs,+ ) -> List[Dict[str, Any]]:+ """+ Discover all URLs under a domain without deep crawling.++ Uses DomainMapper to combine sitemap, Common Crawl, Wayback Machine,+ certificate transparency, path probing, robots.txt mining, feed discovery,+ and homepage link extraction.++ Args:+ domain: Domain to map (e.g., "example.com")+ config: DomainMapperConfig object. kwargs override config fields.++ Returns:+ List of discovered URL dicts with metadata.+ """+ if not self._domain_mapper:+ self._domain_mapper = DomainMapper(+ logger=self.logger,+ base_directory=self.crawl4ai_folder,+ )++ mapper_config = config.clone(**kwargs) if config and kwargs else (+ config or DomainMapperConfig(**kwargs) if kwargs else DomainMapperConfig()+ )++ return await self._domain_mapper.scan(domain, mapper_config)\ No newline at end of filediff --git a/crawl4ai/domain_mapper.py b/crawl4ai/domain_mapper.pynew file mode 100644index 00000000..6e3fc0a0--- /dev/null+++ b/crawl4ai/domain_mapper.py@@ -0,0 +1,1109 @@+"""+domain_mapper.py+Comprehensive domain URL discovery for Crawl4AI++Discovers all URLs under a domain using 8 sources without deep crawling:+ sitemap — per-host sitemap.xml / sitemap_index.xml / robots.txt Sitemap: directives+ cc — Common Crawl CDX API+ wayback — Wayback Machine CDX API+ crt — Certificate Transparency (crt.sh) subdomain discovery+ probe — common-path probing with soft-404 detection+ robots — robots.txt Disallow:/Allow: path mining+ feed — RSS/Atom feed parsing+ homepage — homepage link extraction via quick_extract_links()+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+import pathlib+import re+import time+import uuid+from dataclasses import dataclass, field+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any, Dict, List, Optional, Set, Tuple, Union+from urllib.parse import urljoin, urlparse, quote++import httpx++try:+ from lxml import etree+ LXML = True+except ImportError:+ LXML = False++try:+ import rank_bm25+ HAS_BM25 = True+except ImportError:+ HAS_BM25 = False++from .async_logger import AsyncLoggerBase, AsyncLogger+from .async_url_seeder import AsyncUrlSeeder, _parse_head+from .utils import (+ normalize_url,+ get_base_domain,+ is_external_url,+ quick_extract_links,+)++from typing import TYPE_CHECKING+if TYPE_CHECKING:+ from .async_configs import DomainMapperConfig++# ──────────────────────────────────────────────────────────────── constants++WAYBACK_CDX_URL = "https://web.archive.org/cdx/search/cdx"+CRT_SH_URL = "https://crt.sh/"++DEFAULT_PROBE_PATHS = [+ "/", "/docs", "/api", "/login", "/dashboard", "/blog",+ "/features", "/pricing", "/about", "/contact", "/auth/login",+ "/openapi.json", "/swagger.json", "/api-docs", "/graphql",+ "/status", "/health", "/changelog", "/terms", "/privacy",+ "/faq", "/help", "/support", "/products", "/services",+]++DEFAULT_COMMON_SUBDOMAINS = [+ "www", "app", "api", "docs", "blog", "admin", "staging", "dev",+ "cloud", "mail", "cdn", "static", "portal", "dashboard", "help",+ "support", "shop", "store",+]++FEED_PATHS = [+ "/feed", "/rss", "/atom.xml", "/feed.xml", "/rss.xml",+ "/index.xml", "/feed/rss", "/blog/feed", "/feed/atom",+]++VALID_SOURCES = {"sitemap", "cc", "wayback", "crt", "probe", "robots", "feed", "homepage"}++# Minimal nonsense filter — DomainMapper WANTS /login, /admin etc.+_NONSENSE_SUFFIXES = (+ "/robots.txt", "/sitemap.xml", "/sitemap_index.xml",+ "/favicon.ico", "/apple-touch-icon.png", "/browserconfig.xml",+ "/manifest.json", "/ads.txt", "/humans.txt",+ "/crossdomain.xml",+)++_NONSENSE_CONTAINS = (+ "/.well-known/", "/.git/", "/.svn/", "/.hg/",+)++# Static asset extensions to filter (JS, CSS, fonts, images, media)+_ASSET_EXTENSIONS = (+ ".js", ".css", ".scss", ".sass", ".less", ".map",+ ".woff", ".woff2", ".ttf", ".eot", ".otf",+ ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp", ".ico", ".avif",+ ".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm",+ ".mp3", ".wav", ".ogg", ".m4a", ".flac",+ ".zip", ".tar", ".gz", ".rar", ".7z", ".bz2",+ ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",+)+++# ──────────────────────────────────────────────────────────────── dataclass++@dataclass+class Soft404Fingerprint:+ """Fingerprint of a known-bad URL response for soft-404 detection."""+ status_code: int+ title: Optional[str]+ content_length: int+ body_hash: str+++# ──────────────────────────────────────────────────────────────── class++class DomainMapper:+ """+ Comprehensive domain URL discovery without deep crawling.++ Discovers all URLs under a domain using 8 sources:+ sitemap, cc, wayback, crt, probe, robots, feed, homepage.++ Usage::++ async with DomainMapper() as mapper:+ results = await mapper.scan("example.com")++ # Or via AsyncWebCrawler:+ async with AsyncWebCrawler() as crawler:+ results = await crawler.amap_domain("example.com")+ """++ def __init__(+ self,+ client: Optional[httpx.AsyncClient] = None,+ logger: Optional[AsyncLoggerBase] = None,+ base_directory: Optional[Union[str, Path]] = None,+ ):+ self._owns_client = client is None+ self.client = client or httpx.AsyncClient(+ http2=True,+ timeout=15,+ headers={+ "User-Agent": (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "+ "AppleWebKit/537.36 (KHTML, like Gecko) "+ "Chrome/123.0.0.0 Safari/537.36"+ ),+ },+ )+ self.logger = logger or AsyncLogger(verbose=False)+ self.base_directory = Path(+ base_directory or os.getenv("CRAWL4_AI_BASE_DIRECTORY", Path.home())+ )+ self.cache_dir = self.base_directory / ".crawl4ai" / "domain_mapper_cache"+ self.cache_dir.mkdir(parents=True, exist_ok=True)++ self._seeder: Optional[AsyncUrlSeeder] = None+ self._rate_sem: Optional[asyncio.Semaphore] = None++ # ──────────────────────── lifecycle++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb):+ await self.close()+ return False++ async def close(self):+ if self._seeder:+ await self._seeder.close()+ self._seeder = None+ if self._owns_client and self.client:+ await self.client.aclose()++ # ──────────────────────── logging++ def _log(self, level: str, message: str, tag: str = "MAPPER", **kwargs):+ if self.logger:+ fn = getattr(self.logger, level, None)+ if fn:+ fn(message=message, tag=tag, params=kwargs.get("params", {}))++ # ──────────────────────── seeder composition++ async def _get_seeder(self) -> AsyncUrlSeeder:+ if self._seeder is None:+ self._seeder = AsyncUrlSeeder(+ client=self.client,+ logger=self.logger,+ base_directory=self.base_directory,+ )+ return self._seeder++ # ════════════════════════════════════════════════════════════════════════+ # MAIN ENTRY POINT+ # ════════════════════════════════════════════════════════════════════════++ async def scan(+ self,+ domain: str,+ config: Optional["DomainMapperConfig"] = None,+ **kwargs,+ ) -> List[Dict[str, Any]]:+ """+ Discover all URLs under a domain.++ Args:+ domain: Domain to scan (e.g., "superdesign.dev")+ config: DomainMapperConfig. kwargs override config fields.++ Returns:+ List of dicts with url, host, source, status, head_data, relevance_score.+ """+ from .async_configs import DomainMapperConfig as _Cfg+ if config:+ config = config.clone(**kwargs) if kwargs else config+ else:+ config = _Cfg(**kwargs) if kwargs else _Cfg()++ if config.verbose is not None and self.logger:+ self.logger.verbose = config.verbose++ # Parse + validate sources+ sources = {s.strip().lower() for s in config.source.split("+") if s.strip()}+ invalid = sources - VALID_SOURCES+ if invalid:+ raise ValueError(f"Invalid source(s): {invalid}. Valid: {VALID_SOURCES}")++ # Rate limiter+ if config.hits_per_sec and config.hits_per_sec > 0:+ self._rate_sem = asyncio.Semaphore(config.hits_per_sec)+ else:+ self._rate_sem = None++ # Normalize domain+ base_domain = re.sub(r"^https?://", "", domain).strip("/").lower()++ self._log("info", "Scanning domain: {domain} with sources: {sources}",+ params={"domain": base_domain, "sources": config.source})++ # ── Phase 1: Host Discovery ──────────────────────────────────────+ hosts = await self._discover_hosts(base_domain, sources, config)+ self._log("info", "Discovered {count} live hosts",+ params={"count": len(hosts)})++ if not hosts:+ self._log("warning", "No live hosts found for {domain}",+ params={"domain": base_domain})+ return []++ # ── Phase 2: Per-Host Scanning ───────────────────────────────────+ all_results: List[Dict[str, Any]] = []+ scan_tasks = []+ for host in hosts:+ scan_tasks.append(self._scan_host(host, base_domain, sources, config))++ host_results = await asyncio.gather(*scan_tasks, return_exceptions=True)+ for i, result in enumerate(host_results):+ if isinstance(result, Exception):+ self._log("error", "Error scanning host {host}: {err}",+ params={"host": list(hosts)[i], "err": str(result)})+ else:+ all_results.extend(result)++ self._log("info", "Collected {count} raw URLs from all hosts",+ params={"count": len(all_results)})++ # ── Phase 3: Post-Processing ─────────────────────────────────────+ results = self._normalize_and_dedup(all_results, base_domain)+ self._log("info", "{count} URLs after normalization/dedup",+ params={"count": len(results)})++ if config.filter_nonsense_urls:+ results = [r for r in results if not self._is_nonsense(r["url"])]++ # Head extraction+ if config.extract_head:+ results = await self._extract_heads(results, config)++ # BM25 scoring+ if config.query and config.extract_head:+ results = await self._apply_scoring(results, config)++ # Limit+ if config.max_urls > 0:+ results = results[:config.max_urls]++ self._log("info", "Scan complete: {count} URLs found across {hosts} hosts",+ params={"count": len(results),+ "hosts": len({r["host"] for r in results})})+ return results++ # ════════════════════════════════════════════════════════════════════════+ # PHASE 1: HOST DISCOVERY+ # ════════════════════════════════════════════════════════════════════════++ async def _discover_hosts(+ self, base_domain: str, sources: Set[str], config: "DomainMapperConfig"+ ) -> Set[str]:+ """Discover all subdomains/hosts under base_domain."""+ hosts: Set[str] = {base_domain}++ discovery_tasks = []++ if "crt" in sources:+ discovery_tasks.append(("crt", self._discover_via_crt(base_domain, config)))+ if "wayback" in sources:+ discovery_tasks.append(("wayback", self._discover_via_wayback(base_domain, config)))+ if "cc" in sources:+ discovery_tasks.append(("cc", self._discover_via_cc(base_domain, config)))++ # Always guess common subdomains when crt is enabled+ if "crt" in sources or "probe" in sources:+ prefixes = list(DEFAULT_COMMON_SUBDOMAINS)+ if config.common_subdomains:+ prefixes.extend(config.common_subdomains)+ discovery_tasks.append(("dns", self._guess_subdomains(base_domain, prefixes, config)))++ # Run all discovery in parallel+ if discovery_tasks:+ coros = [t[1] for t in discovery_tasks]+ names = [t[0] for t in discovery_tasks]+ results = await asyncio.gather(*coros, return_exceptions=True)+ for name, result in zip(names, results):+ if isinstance(result, Exception):+ self._log("warning", "{source} discovery failed: {err}",+ params={"source": name, "err": str(result)})+ else:+ self._log("info", "{source} discovered {count} hosts: {hosts}",+ params={"source": name, "count": len(result),+ "hosts": ", ".join(sorted(result)[:10])})+ hosts.update(result)++ # Validate all hosts are actually alive+ validated = await self._validate_hosts(hosts, config)+ return validated++ async def _discover_via_crt(self, base_domain: str, config: "DomainMapperConfig") -> Set[str]:+ """Discover subdomains via Certificate Transparency logs (crt.sh)."""+ hosts: Set[str] = set()+ url = f"{CRT_SH_URL}?q=%.{base_domain}&output=json"+ try:+ resp = await self.client.get(url, timeout=15, follow_redirects=True)+ if resp.status_code != 200:+ self._log("warning", "crt.sh returned HTTP {code}",+ params={"code": resp.status_code})+ return hosts++ entries = resp.json()+ for entry in entries:+ for field_name in ("common_name", "name_value"):+ val = entry.get(field_name, "")+ # name_value can have newline-separated SANs+ for name in val.split("\n"):+ name = name.strip().lower()+ # Skip wildcards+ if name.startswith("*."):+ name = name[2:]+ if not name:+ continue+ # Must be a subdomain of base_domain+ if name == base_domain or name.endswith(f".{base_domain}"):+ hosts.add(name)+ except Exception as e:+ self._log("warning", "crt.sh query failed: {err}", params={"err": str(e)})+ return hosts++ async def _discover_via_wayback(self, base_domain: str, config: "DomainMapperConfig") -> Set[str]:+ """Discover hosts from Wayback Machine CDX API."""+ hosts: Set[str] = set()+ # Also store URLs for later use in Phase 2+ self._wayback_urls: List[str] = []+ params = {+ "url": f"*.{base_domain}/*",+ "output": "text",+ "fl": "original",+ "collapse": "urlkey",+ "limit": "10000",+ }+ try:+ resp = await self.client.get(+ WAYBACK_CDX_URL, params=params, timeout=30, follow_redirects=True+ )+ if resp.status_code != 200:+ return hosts+ for line in resp.text.strip().splitlines():+ url = line.strip()+ if not url:+ continue+ self._wayback_urls.append(url)+ parsed = urlparse(url)+ host = parsed.netloc.lower().split(":")[0]+ if host and (host == base_domain or host.endswith(f".{base_domain}")):+ hosts.add(host)+ except Exception as e:+ self._log("warning", "Wayback CDX query failed: {err}", params={"err": str(e)})+ return hosts++ async def _discover_via_cc(self, base_domain: str, config: "DomainMapperConfig") -> Set[str]:+ """Extract unique hostnames from Common Crawl results."""+ hosts: Set[str] = set()+ try:+ seeder = await self._get_seeder()+ # We need the CC index+ if seeder.index_id is None:+ seeder.index_id = await seeder._latest_index()++ from .async_configs import SeedingConfig+ cc_cfg = SeedingConfig(+ source="cc", max_urls=-1, filter_nonsense_urls=False,+ extract_head=False, live_check=False, force=config.force,+ )+ results = await seeder.urls(base_domain, cc_cfg)+ for r in results:+ url = r["url"] if isinstance(r, dict) else r+ parsed = urlparse(url)+ host = parsed.netloc.lower().split(":")[0]+ if host and (host == base_domain or host.endswith(f".{base_domain}")):+ hosts.add(host)+ except Exception as e:+ self._log("warning", "CC host discovery failed: {err}", params={"err": str(e)})+ return hosts++ async def _guess_subdomains(+ self, base_domain: str, prefixes: List[str], config: "DomainMapperConfig"+ ) -> Set[str]:+ """Guess common subdomains via DNS resolution."""+ hosts: Set[str] = set()++ async def check(prefix: str):+ fqdn = f"{prefix}.{base_domain}"+ try:+ loop = asyncio.get_event_loop()+ await asyncio.wait_for(+ loop.getaddrinfo(fqdn, None),+ timeout=config.dns_timeout,+ )+ return fqdn+ except Exception:+ return None++ results = await asyncio.gather(*[check(p) for p in prefixes])+ for r in results:+ if r:+ hosts.add(r)+ return hosts++ async def _validate_hosts(self, hosts: Set[str], config: "DomainMapperConfig") -> Set[str]:+ """Validate hosts are reachable via HTTP."""+ validated: Set[str] = set()+ # Track redirects so we can map canonical hosts+ self._host_redirects: Dict[str, str] = {}++ async def check(host: str):+ for scheme in ("https", "http"):+ url = f"{scheme}://{host}/"+ try:+ resp = await self.client.head(+ url, timeout=config.http_timeout, follow_redirects=False+ )+ # Record redirect target for dedup+ if resp.status_code in (301, 302, 303, 307, 308):+ loc = resp.headers.get("location", "")+ if loc:+ target_host = urlparse(urljoin(url, loc)).netloc.lower().split(":")[0]+ if target_host != host:+ self._host_redirects[host] = target_host+ return host+ except Exception:+ continue+ return None++ results = await asyncio.gather(*[check(h) for h in hosts])+ for r in results:+ if r:+ validated.add(r)+ return validated++ # ════════════════════════════════════════════════════════════════════════+ # PHASE 2: PER-HOST SCANNING+ # ════════════════════════════════════════════════════════════════════════++ async def _scan_host(+ self, host: str, base_domain: str, sources: Set[str], config: "DomainMapperConfig"+ ) -> List[Dict[str, Any]]:+ """Run all enabled sources against a single host."""+ results: List[Dict[str, Any]] = []++ # Soft-404 fingerprint (must run first)+ soft_404_fp = None+ if config.soft_404_detection:+ soft_404_fp = await self._fingerprint_soft_404(host, config)+ if soft_404_fp and soft_404_fp.status_code == 200:+ self._log("info", "Soft-404 fingerprint for {host}: title={title}",+ params={"host": host, "title": soft_404_fp.title or "(none)"})+ else:+ soft_404_fp = None # Host returns proper 404s, no soft-404 issue++ # robots.txt (feeds into sitemap + probe)+ sitemap_urls: List[str] = []+ disallow_paths: List[str] = []+ if "robots" in sources or "sitemap" in sources:+ sitemap_urls, disallow_paths = await self._scan_robots_txt(host, config)++ # Gather per-host sources in parallel+ tasks: Dict[str, Any] = {}++ if "sitemap" in sources:+ tasks["sitemap"] = self._scan_sitemaps(host, sitemap_urls, config)++ if "probe" in sources or "robots" in sources:+ # If host has soft-404 fingerprint, add robots paths to probe (which does soft-404 checking)+ # rather than treating them as known-good+ probe_paths = list(DEFAULT_PROBE_PATHS)+ if config.probe_paths:+ probe_paths.extend(config.probe_paths)+ if "robots" in sources and disallow_paths:+ probe_paths.extend(disallow_paths)+ # Deduplicate+ probe_paths = list(dict.fromkeys(probe_paths))+ tasks["probe"] = self._probe_paths(host, probe_paths, soft_404_fp, config)++ if "feed" in sources:+ tasks["feed"] = self._discover_feeds(host, config)++ if "homepage" in sources:+ tasks["homepage"] = self._scan_homepage(host, base_domain, config)++ # Run in parallel+ if tasks:+ source_names = list(tasks.keys())+ coros = list(tasks.values())+ task_results = await asyncio.gather(*coros, return_exceptions=True)++ for name, result in zip(source_names, task_results):+ if isinstance(result, Exception):+ self._log("warning", "{source} scan failed on {host}: {err}",+ params={"source": name, "host": host, "err": str(result)})+ continue++ # For sitemap URLs on hosts with soft-404: sample-check a few URLs+ # If all samples are soft-404, skip the entire batch+ if name == "sitemap" and soft_404_fp and len(result) > 5:+ import random+ sample = random.sample(result, min(5, len(result)))+ soft_404_count = 0+ for sample_url in sample:+ try:+ resp = await self.client.get(+ sample_url, timeout=config.http_timeout,+ follow_redirects=True,+ headers={"Accept-Encoding": "identity"},+ )+ if self._is_soft_404(resp.status_code, resp.content, soft_404_fp):+ soft_404_count += 1+ except Exception:+ pass+ if soft_404_count == len(sample):+ self._log("info",+ "Skipping {count} sitemap URLs from {host} (all samples are soft-404)",+ params={"count": len(result), "host": host})+ continue++ for url in result:+ results.append({+ "url": url,+ "host": host,+ "source": name,+ "status": "valid",+ "head_data": {},+ })++ # Add Wayback URLs that belong to this host+ if "wayback" in sources and hasattr(self, "_wayback_urls"):+ for url in self._wayback_urls:+ parsed = urlparse(url)+ url_host = parsed.netloc.lower().split(":")[0]+ if url_host == host:+ results.append({+ "url": url,+ "host": host,+ "source": "wayback",+ "status": "valid",+ "head_data": {},+ })++ return results++ # ──────────────────────── Soft-404 Detection++ async def _fingerprint_soft_404(+ self, host: str, config: "DomainMapperConfig"+ ) -> Optional[Soft404Fingerprint]:+ """Fetch a known-bad URL to fingerprint soft-404 responses."""+ random_path = f"/c4ai-probe-{uuid.uuid4().hex[:12]}"+ url = f"https://{host}{random_path}"+ try:+ resp = await self.client.get(+ url, timeout=config.http_timeout, follow_redirects=True+ )+ body = resp.content[:2048]+ title = None+ m = re.search(rb"<title[^>]*>(.*?)</title>", body, re.I | re.S)+ if m:+ title = m.group(1).decode("utf-8", "replace").strip()+ return Soft404Fingerprint(+ status_code=resp.status_code,+ title=title,+ content_length=int(resp.headers.get("content-length", -1)),+ body_hash=hashlib.md5(body).hexdigest(),+ )+ except Exception:+ return None++ def _is_soft_404(+ self, status_code: int, body: bytes, fingerprint: Optional[Soft404Fingerprint]+ ) -> bool:+ """Check if a response matches the soft-404 fingerprint."""+ if fingerprint is None:+ return False+ if status_code != 200:+ return False++ # Check body hash+ body_hash = hashlib.md5(body[:2048]).hexdigest()+ if body_hash == fingerprint.body_hash:+ return True++ # Check title+ m = re.search(rb"<title[^>]*>(.*?)</title>", body[:2048], re.I | re.S)+ if m and fingerprint.title:+ title = m.group(1).decode("utf-8", "replace").strip()+ if title == fingerprint.title:+ return True++ return False++ # ──────────────────────── robots.txt++ async def _scan_robots_txt(+ self, host: str, config: "DomainMapperConfig"+ ) -> Tuple[List[str], List[str]]:+ """Parse robots.txt for Sitemap: and Disallow: directives."""+ sitemap_urls: List[str] = []+ disallow_paths: List[str] = []++ for scheme in ("https", "http"):+ url = f"{scheme}://{host}/robots.txt"+ try:+ resp = await self.client.get(url, timeout=config.http_timeout, follow_redirects=True)+ if resp.status_code != 200:+ continue++ for line in resp.text.splitlines():+ line = line.strip()+ if line.lower().startswith("sitemap:"):+ sm_url = line.split(":", 1)[1].strip()+ if sm_url:+ sitemap_urls.append(sm_url)+ elif line.lower().startswith("disallow:"):+ path = line.split(":", 1)[1].strip()+ # Keep only concrete paths (no wildcards, no empty)+ if path and "*" not in path and len(path) > 1:+ disallow_paths.append(path)+ elif line.lower().startswith("allow:"):+ path = line.split(":", 1)[1].strip()+ if path and "*" not in path and len(path) > 1:+ disallow_paths.append(path)++ self._log("info", "robots.txt for {host}: {sm} sitemaps, {dp} paths",+ params={"host": host, "sm": len(sitemap_urls),+ "dp": len(disallow_paths)})+ return sitemap_urls, list(dict.fromkeys(disallow_paths))++ except Exception:+ continue++ return sitemap_urls, disallow_paths++ # ──────────────────────── Sitemaps++ async def _scan_sitemaps(+ self, host: str, sitemap_urls: List[str], config: "DomainMapperConfig"+ ) -> List[str]:+ """Discover URLs from sitemaps on a host."""+ urls: List[str] = []++ # If no sitemaps from robots.txt, try defaults+ if not sitemap_urls:+ for scheme in ("https", "http"):+ for suffix in ("/sitemap.xml", "/sitemap_index.xml"):+ candidate = f"{scheme}://{host}{suffix}"+ try:+ resp = await self.client.head(+ candidate, timeout=config.http_timeout, follow_redirects=True+ )+ if 200 <= resp.status_code < 300:+ sitemap_urls.append(candidate)+ break+ except Exception:+ continue+ if sitemap_urls:+ break++ if not sitemap_urls:+ return urls++ # Use AsyncUrlSeeder's sitemap parsing+ seeder = await self._get_seeder()+ for sm_url in sitemap_urls:+ try:+ async for u in seeder._iter_sitemap(sm_url):+ urls.append(u)+ except Exception as e:+ self._log("warning", "Error parsing sitemap {url}: {err}",+ params={"url": sm_url, "err": str(e)})++ self._log("info", "Sitemaps for {host}: {count} URLs",+ params={"host": host, "count": len(urls)})+ return urls++ # ──────────────────────── Path Probing++ async def _probe_paths(+ self,+ host: str,+ paths: List[str],+ soft_404_fp: Optional[Soft404Fingerprint],+ config: "DomainMapperConfig",+ ) -> List[str]:+ """Probe common paths on a host, filtering soft-404s."""+ valid_urls: List[str] = []++ async def probe_one(path: str) -> Optional[str]:+ url = f"https://{host}{path}"+ try:+ if self._rate_sem:+ async with self._rate_sem:+ return await self._do_probe(url, soft_404_fp, config)+ else:+ return await self._do_probe(url, soft_404_fp, config)+ except Exception:+ return None++ results = await asyncio.gather(*[probe_one(p) for p in paths])+ for r in results:+ if r:+ valid_urls.append(r)++ self._log("info", "Probed {total} paths on {host}: {valid} valid",+ params={"total": len(paths), "host": host, "valid": len(valid_urls)})+ return valid_urls++ async def _do_probe(+ self, url: str, soft_404_fp: Optional[Soft404Fingerprint], config: "DomainMapperConfig"+ ) -> Optional[str]:+ """Probe a single URL: HEAD then GET to check soft-404."""+ try:+ resp = await self.client.head(+ url, timeout=config.http_timeout, follow_redirects=True+ )+ except Exception:+ return None++ if resp.status_code >= 400:+ return None++ # For 2xx responses, verify against soft-404+ if soft_404_fp and resp.status_code == 200:+ try:+ get_resp = await self.client.get(+ url, timeout=config.http_timeout, follow_redirects=True,+ headers={"Accept-Encoding": "identity"},+ )+ body = get_resp.content[:2048]+ if self._is_soft_404(get_resp.status_code, body, soft_404_fp):+ self._log("debug", "Soft-404 detected: {url}", params={"url": url})+ return None+ except Exception:+ pass++ # Return the final URL after redirects+ return str(resp.url)++ # ──────────────────────── Feed Discovery++ async def _discover_feeds(self, host: str, config: "DomainMapperConfig") -> List[str]:+ """Discover URLs from RSS/Atom feeds."""+ discovered: List[str] = []++ for feed_path in FEED_PATHS:+ url = f"https://{host}{feed_path}"+ try:+ resp = await self.client.get(+ url, timeout=config.http_timeout, follow_redirects=True+ )+ if resp.status_code != 200:+ continue++ content_type = resp.headers.get("content-type", "").lower()+ body = resp.text++ # Quick check: is this XML/RSS/Atom?+ if not any(x in content_type for x in ("xml", "rss", "atom")) and \+ not body.strip().startswith("<?xml") and \+ "<rss" not in body[:500] and "<feed" not in body[:500]:+ continue++ feed_urls = self._parse_feed_xml(body, str(resp.url))+ if feed_urls:+ self._log("info", "Feed {path} on {host}: {count} URLs",+ params={"path": feed_path, "host": host,+ "count": len(feed_urls)})+ discovered.extend(feed_urls)+ break # One good feed is enough per host++ except Exception:+ continue++ return discovered++ def _parse_feed_xml(self, xml_text: str, base_url: str) -> List[str]:+ """Parse RSS or Atom feed XML to extract entry URLs."""+ urls: List[str] = []+ try:+ if LXML:+ parser = etree.XMLParser(recover=True)+ root = etree.fromstring(xml_text.encode("utf-8", "replace"), parser=parser)++ # RSS: <item><link>URL</link></item>+ for link in root.xpath("//*[local-name()='item']/*[local-name()='link']"):+ if link.text and link.text.strip():+ urls.append(urljoin(base_url, link.text.strip()))++ # Atom: <entry><link href="URL"/></entry>+ for link in root.xpath("//*[local-name()='entry']/*[local-name()='link']"):+ href = link.get("href")+ if href:+ urls.append(urljoin(base_url, href.strip()))++ # RSS: <item><guid isPermaLink="true">URL</guid></item>+ if not urls:+ for guid in root.xpath("//*[local-name()='item']/*[local-name()='guid']"):+ is_permalink = guid.get("isPermaLink", "true").lower()+ if is_permalink == "true" and guid.text and guid.text.strip().startswith("http"):+ urls.append(guid.text.strip())+ else:+ import xml.etree.ElementTree as ET+ root = ET.fromstring(xml_text)+ for elem in root.iter():+ if "}" in elem.tag:+ elem.tag = elem.tag.split("}")[1]++ for item in root.findall(".//item"):+ link = item.find("link")+ if link is not None and link.text:+ urls.append(urljoin(base_url, link.text.strip()))++ for entry in root.findall(".//entry"):+ link = entry.find("link")+ if link is not None:+ href = link.get("href")+ if href:+ urls.append(urljoin(base_url, href.strip()))+ except Exception:+ pass+ return urls++ # ──────────────────────── Homepage Link Extraction++ async def _scan_homepage(+ self, host: str, base_domain: str, config: "DomainMapperConfig"+ ) -> List[str]:+ """Extract internal links from a host's homepage."""+ urls: List[str] = []+ base_url = f"https://{host}/"++ try:+ resp = await self.client.get(+ base_url, timeout=config.http_timeout, follow_redirects=True+ )+ if resp.status_code != 200:+ return urls++ html = resp.text++ # Extract <a href> links+ links = quick_extract_links(html, str(resp.url))+ for link in links.get("internal", []):+ href = link.get("href", "")+ if href:+ urls.append(href)++ # Also mine <link> tags from <head>+ head_data = _parse_head(html)+ for rel, entries in head_data.get("link", {}).items():+ if rel in ("alternate", "preload", "prefetch", "next", "prev"):+ for entry in entries:+ href = entry.get("href", "")+ if href:+ full_url = urljoin(str(resp.url), href)+ if not is_external_url(full_url, base_domain):+ urls.append(full_url)++ self._log("info", "Homepage {host}: {count} internal links",+ params={"host": host, "count": len(urls)})++ except Exception as e:+ self._log("warning", "Failed to fetch homepage for {host}: {err}",+ params={"host": host, "err": str(e)})++ return urls++ # ════════════════════════════════════════════════════════════════════════+ # PHASE 3: POST-PROCESSING+ # ════════════════════════════════════════════════════════════════════════++ def _normalize_and_dedup(+ self, results: List[Dict[str, Any]], base_domain: str+ ) -> List[Dict[str, Any]]:+ """Normalize URLs and deduplicate, merging source attribution."""+ seen: Dict[str, Dict[str, Any]] = {}++ for r in results:+ url = r["url"]+ # Normalize+ try:+ normalized = normalize_url(url, f"https://{base_domain}/")+ except Exception:+ normalized = url++ if not normalized:+ continue++ # Strip trailing slash for dedup (keep in output)+ key = normalized.rstrip("/").lower()++ if key in seen:+ # Merge source+ existing_sources = set(seen[key]["source"].split("+"))+ existing_sources.add(r["source"])+ seen[key]["source"] = "+".join(sorted(existing_sources))+ else:+ r_copy = r.copy()+ r_copy["url"] = normalized+ seen[key] = r_copy++ return list(seen.values())++ def _is_nonsense(self, url: str) -> bool:+ """Reduced nonsense filter for DomainMapper."""+ parsed = urlparse(url)+ path = parsed.path.lower()++ # Nonsense suffixes+ if any(path.endswith(s) for s in _NONSENSE_SUFFIXES):+ return True++ # Nonsense contains+ if any(c in path for c in _NONSENSE_CONTAINS):+ return True++ # Sitemap variations+ if "/sitemap" in path and path.endswith((".xml", ".xml.gz", ".txt")):+ return True++ # Static assets (JS, CSS, fonts, images, media, archives)+ if any(path.endswith(ext) for ext in _ASSET_EXTENSIONS):+ return True++ # Next.js / webpack chunks+ if "/_next/" in path or "/webpack" in path:+ return True++ # Hidden dotfiles+ parts = path.split("/")+ if any(p.startswith(".") and p not in (".", "..") for p in parts if p):+ return True++ # Wayback garbage: URLs with encoded newlines/backslashes+ if any(x in url for x in ("%5C", "%0A", "%0D", "\\n", "\\r")):+ return True++ return False++ async def _extract_heads(+ self, results: List[Dict[str, Any]], config: "DomainMapperConfig"+ ) -> List[Dict[str, Any]]:+ """Extract <head> metadata for all valid URLs."""+ seeder = await self._get_seeder()+ sem = asyncio.Semaphore(config.concurrency)++ async def fetch_one(r: Dict[str, Any]):+ if r.get("head_data"):+ return # Already has head data+ async with sem:+ if self._rate_sem:+ async with self._rate_sem:+ await self._do_fetch_head(r, seeder, config)+ else:+ await self._do_fetch_head(r, seeder, config)++ await asyncio.gather(*[fetch_one(r) for r in results], return_exceptions=True)+ return results++ async def _do_fetch_head(+ self, r: Dict[str, Any], seeder: AsyncUrlSeeder, config: "DomainMapperConfig"+ ):+ """Fetch and parse <head> for a single result."""+ try:+ ok, html, final_url = await seeder._fetch_head(r["url"], int(config.http_timeout))+ if ok:+ r["head_data"] = await asyncio.to_thread(_parse_head, html)+ if final_url and final_url != r["url"]:+ r["url"] = final_url+ else:+ r["status"] = "not_valid"+ except Exception:+ r["status"] = "not_valid"++ async def _apply_scoring(+ self, results: List[Dict[str, Any]], config: "DomainMapperConfig"+ ) -> List[Dict[str, Any]]:+ """Apply BM25 scoring to results with head data."""+ if not HAS_BM25 or not config.query:+ return results++ seeder = await self._get_seeder()++ # Build text corpus from head data+ text_contexts = []+ scoreable = []+ for r in results:+ if r.get("head_data"):+ text = seeder._extract_text_context(r["head_data"])+ if text:+ text_contexts.append(text)+ scoreable.append(r)++ if text_contexts:+ scores = await asyncio.to_thread(+ seeder._calculate_bm25_score, config.query, text_contexts+ )+ for i, r in enumerate(scoreable):+ if i < len(scores):+ r["relevance_score"] = float(scores[i])++ # Filter by threshold+ if config.score_threshold is not None:+ results = [r for r in results if r.get("relevance_score", 0) >= config.score_threshold]++ # Sort by relevance+ results.sort(key=lambda x: x.get("relevance_score", 0.0), reverse=True)+ return results++ # ════════════════════════════════════════════════════════════════════════+ # CACHING+ # ════════════════════════════════════════════════════════════════════════++ def _cache_key(self, domain: str, config: "DomainMapperConfig") -> str:+ """Generate cache key from domain + config."""+ config_str = f"{config.source}:{config.filter_nonsense_urls}:{config.soft_404_detection}"+ h = hashlib.md5(config_str.encode()).hexdigest()[:8]+ safe_domain = re.sub(r"[/?#]+", "_", domain)+ return f"scan_{safe_domain}_{h}.json"++ def _read_scan_cache(self, domain: str, config: "DomainMapperConfig") -> Optional[List[Dict]]:+ """Read cached scan results if valid."""+ if config.force:+ return None+ path = self.cache_dir / self._cache_key(domain, config)+ if not path.exists():+ return None+ try:+ data = json.loads(path.read_text())+ if data.get("version") != 1:+ return None+ created = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))+ age_hours = (datetime.now(timezone.utc) - created).total_seconds() / 3600+ if age_hours > config.cache_ttl_hours:+ return None+ return data.get("results", [])+ except Exception:+ return None++ def _write_scan_cache(+ self, domain: str, config: "DomainMapperConfig", results: List[Dict]+ ):+ """Write scan results to cache."""+ path = self.cache_dir / self._cache_key(domain, config)+ try:+ data = {+ "version": 1,+ "created_at": datetime.now(timezone.utc).isoformat(),+ "domain": domain,+ "result_count": len(results),+ "results": results,+ }+ path.write_text(json.dumps(data, default=str))+ except Exception:+ passdiff --git a/docs/examples/domain_mapper/domain_mapper_demo.py b/docs/examples/domain_mapper/domain_mapper_demo.pynew file mode 100644index 00000000..0270d472--- /dev/null+++ b/docs/examples/domain_mapper/domain_mapper_demo.py@@ -0,0 +1,82 @@+"""+DomainMapper Demo — Comprehensive domain URL discovery++Discovers all URLs under a domain using 8 sources:+sitemap, Common Crawl, Wayback Machine, Certificate Transparency,+path probing, robots.txt mining, RSS/Atom feeds, homepage link extraction.++Usage:+ python domain_mapper_demo.py [domain] [--source SOURCE] [--query QUERY]++Examples:+ python domain_mapper_demo.py superdesign.dev+ python domain_mapper_demo.py example.com --source sitemap+crt+probe+ python domain_mapper_demo.py docs.crawl4ai.com --query "extraction tutorial"+"""++import asyncio+import argparse+from collections import defaultdict+from crawl4ai import DomainMapper, DomainMapperConfig+++async def main():+ parser = argparse.ArgumentParser(description="DomainMapper Demo")+ parser.add_argument("domain", help="Domain to scan (e.g., example.com)")+ parser.add_argument("--source", default="sitemap+cc+crt+probe+robots+homepage",+ help="Discovery sources (default: sitemap+cc+crt+probe+robots+homepage)")+ parser.add_argument("--query", default=None, help="BM25 relevance query")+ parser.add_argument("--max-urls", type=int, default=-1, help="Max URLs to return")+ parser.add_argument("--no-head", action="store_true", help="Skip head extraction")+ args = parser.parse_args()++ config = DomainMapperConfig(+ source=args.source,+ extract_head=not args.no_head,+ query=args.query,+ max_urls=args.max_urls,+ verbose=True,+ force=True,+ )++ async with DomainMapper() as mapper:+ results = await mapper.scan(args.domain, config)++ # Group by host+ by_host = defaultdict(list)+ for r in results:+ by_host[r["host"]].append(r)++ # Print results+ print("\n" + "=" * 70)+ print(f"RESULTS: {len(results)} URLs across {len(by_host)} hosts")+ print("=" * 70)++ for host in sorted(by_host.keys()):+ urls = by_host[host]+ print(f"\n {host} ({len(urls)} URLs):")+ for r in urls[:10]:+ title = r.get("head_data", {}).get("title", "")+ score = r.get("relevance_score")+ line = f" [{r['source']}] {r['url']}"+ if title:+ line += f"\n Title: {title}"+ if score is not None:+ line += f"\n Score: {score:.3f}"+ print(line)+ if len(urls) > 10:+ print(f" ... and {len(urls) - 10} more")++ # Source breakdown+ source_counts = defaultdict(int)+ for r in results:+ for s in r["source"].split("+"):+ source_counts[s] += 1++ print(f"\nSource breakdown:")+ for source, count in sorted(source_counts.items(), key=lambda x: -x[1]):+ print(f" {source}: {count} URLs")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/docs/md_v2/core/domain-mapping.md b/docs/md_v2/core/domain-mapping.mdnew file mode 100644index 00000000..52e9b8ad--- /dev/null+++ b/docs/md_v2/core/domain-mapping.md@@ -0,0 +1,343 @@+# Domain Mapping: Discover Every URL Under a Domain++## What Is Domain Mapping?++Domain mapping goes beyond URL seeding. Instead of checking a single sitemap or index, `DomainMapper` combines **8 discovery sources** to find every URL under a domain — including subdomains you didn't know existed.++### DomainMapper vs AsyncUrlSeeder++| Aspect | AsyncUrlSeeder | DomainMapper |+|--------|---------------|--------------|+| **Scope** | Single host, listed URLs only | Entire domain + all subdomains |+| **Sources** | Sitemap + Common Crawl | 8 sources (sitemap, CC, Wayback, crt.sh, probe, robots.txt, feeds, homepage) |+| **Subdomain discovery** | No | Yes (Certificate Transparency, DNS, Wayback) |+| **Soft-404 detection** | No | Yes (fingerprints SPA sites) |+| **Best for** | Known domains with good sitemaps | Full domain reconnaissance |++**Real-world example**: For `superdesign.dev`, AsyncUrlSeeder found 4 URLs. DomainMapper found **171 URLs across 11 hosts** — including docs, API servers, staging environments, and analytics dashboards that no sitemap listed.++## Quick Start++```python+import asyncio+from crawl4ai import DomainMapper, DomainMapperConfig++async def main():+ async with DomainMapper() as mapper:+ results = await mapper.scan("example.com")++ print(f"Found {len(results)} URLs")+ for r in results[:10]:+ print(f" [{r['source']}] {r['url']}")+ if r.get("head_data", {}).get("title"):+ print(f" Title: {r['head_data']['title']}")++asyncio.run(main())+```++Or via `AsyncWebCrawler`:++```python+from crawl4ai import AsyncWebCrawler, DomainMapperConfig++async with AsyncWebCrawler() as crawler:+ results = await crawler.amap_domain("example.com")+```++## The 8 Discovery Sources++DomainMapper combines these sources, each catching URLs the others miss:++### 1. `sitemap` — Sitemap Discovery++Checks `/sitemap.xml`, `/sitemap_index.xml`, and `robots.txt` `Sitemap:` directives **on every discovered host** — not just the root domain.++```python+config = DomainMapperConfig(source="sitemap")+```++### 2. `cc` — Common Crawl++Queries the Common Crawl CDX API for `*.domain.tld/*`, catching URLs and subdomains the web's largest public crawl has indexed.++```python+config = DomainMapperConfig(source="cc")+```++### 3. `wayback` — Wayback Machine++Queries the Internet Archive's CDX API. Often has different coverage than Common Crawl — including historical pages that have since been removed.++```python+config = DomainMapperConfig(source="wayback")+```++### 4. `crt` — Certificate Transparency++Queries [crt.sh](https://crt.sh) for SSL certificates issued to `*.domain.tld`. This is the single most effective subdomain discovery technique — it found 14 subdomains for `superdesign.dev` that no other source knew about.++```python+config = DomainMapperConfig(source="crt")+```++### 5. `probe` — Common Path Probing++Tries ~25 well-known paths on each discovered host (`/docs`, `/api`, `/login`, `/dashboard`, `/openapi.json`, etc.). Combined with soft-404 detection to avoid false positives.++```python+config = DomainMapperConfig(source="probe")++# Add custom paths to probe+config = DomainMapperConfig(+ source="probe",+ probe_paths=["/custom-api", "/internal/status"]+)+```++### 6. `robots` — robots.txt Path Mining++Parses `Disallow:` and `Allow:` lines from `robots.txt`. These are confirmed real paths the site acknowledges exist — often revealing admin panels, APIs, and internal tools that aren't linked anywhere.++```python+config = DomainMapperConfig(source="robots")+```++### 7. `feed` — RSS/Atom Feed Parsing++Discovers and parses RSS/Atom feeds at common paths (`/feed`, `/rss`, `/atom.xml`, etc.). Feeds are curated lists of content URLs maintained by the site.++```python+config = DomainMapperConfig(source="feed")+```++### 8. `homepage` — Homepage Link Extraction++Fetches each host's homepage via HTTP and extracts all internal links using `quick_extract_links()`. Also mines `<link rel="alternate|preload|prefetch">` tags from the `<head>` for additional URLs. No browser needed.++```python+config = DomainMapperConfig(source="homepage")+```++### Combining Sources++Sources are combined with `+`:++```python+# Default: most useful combination+config = DomainMapperConfig(source="sitemap+cc+crt+probe")++# Maximum coverage: all 8 sources+config = DomainMapperConfig(+ source="sitemap+cc+wayback+crt+probe+robots+feed+homepage"+)++# Lightweight: just sitemap + probing+config = DomainMapperConfig(source="sitemap+probe")+```++## How It Works: The Three Phases++### Phase 1: Host Discovery++DomainMapper first discovers all subdomains under your domain:++```+superdesign.dev+├── crt.sh → docs, app, cloud, insights, staging-api, ui2web, ...+├── Wayback CDX → api, app, docs, www, ...+├── Common Crawl → app, www, ...+└── DNS guessing → www, app, api, docs, blog, admin, cloud, ...++Result: 13 validated hosts+```++Each discovered host is validated with an HTTP HEAD request. Hosts that don't respond are dropped.++### Phase 2: Per-Host Scanning++For each validated host, DomainMapper runs all enabled sources in parallel:++```+docs.superdesign.dev+├── Soft-404 fingerprint → (404 returns proper error — no SPA issue)+├── robots.txt → 1 sitemap URL, 1 disallow path+├── Sitemap parsing → 19 URLs+├── Path probing → 2 valid (/docs, /)+├── Feed discovery → (no feeds found)+└── Homepage extraction → 26 internal links+```++### Phase 3: Post-Processing++All discovered URLs go through:++1. **URL normalization** — using `normalize_url()` to canonicalize+2. **Deduplication** — by normalized URL, merging source attribution+3. **Nonsense filtering** — removes static assets (JS, CSS, images, fonts), webpack chunks, Wayback garbage+4. **Head extraction** — parallel `<head>` fetching for metadata (optional)+5. **BM25 scoring** — relevance scoring against a query (optional)++## Soft-404 Detection++Many modern SPAs return HTTP 200 for every URL — even pages that don't exist. DomainMapper detects this:++1. **Fingerprinting**: Fetches a guaranteed-nonexistent URL (e.g., `/c4ai-probe-a1b2c3d4`) on each host+2. **Recording**: Captures the response title and body hash+3. **Filtering**: When probing real paths, compares against the fingerprint. If they match → soft-404, filtered out++For `superdesign.dev`, this correctly:+- Blocked **all 25+ probe paths** on `app.superdesign.dev` (SPA that returns 200 for everything)+- Blocked **476 sitemap URLs** from `app.superdesign.dev` (all rendering the same shell)+- Kept all 19 legitimate URLs from `docs.superdesign.dev`++```python+# Soft-404 detection is on by default+config = DomainMapperConfig(soft_404_detection=True)++# Disable if you want raw results+config = DomainMapperConfig(soft_404_detection=False)+```++## Configuration Reference++### DomainMapperConfig++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `source` | str | `"sitemap+cc+crt+probe"` | Discovery sources joined by `+` |+| `max_urls` | int | `-1` | Maximum URLs to return (-1 = unlimited) |+| `concurrency` | int | `50` | Max concurrent requests across all hosts |+| `hits_per_sec` | int | `10` | Rate limit in requests/second |+| `force` | bool | `False` | Bypass all caches |+| `extract_head` | bool | `True` | Fetch and parse `<head>` metadata |+| `filter_nonsense_urls` | bool | `True` | Filter static assets and utility URLs |+| `soft_404_detection` | bool | `True` | Fingerprint and filter soft-404 pages |+| `query` | str | `None` | BM25 relevance query (requires `extract_head=True`) |+| `score_threshold` | float | `None` | Minimum relevance score (0.0-1.0) |+| `scoring_method` | str | `"bm25"` | Scoring algorithm |+| `probe_paths` | List[str] | `None` | Extra paths to probe on each host |+| `common_subdomains` | List[str] | `None` | Extra subdomain prefixes to guess |+| `use_browser_for_homepage` | bool | `False` | Use Playwright for JS-rendered homepages |+| `verbose` | bool | `None` | Override logger verbose setting |+| `cache_ttl_hours` | int | `24` | Hours before cached results expire |+| `dns_timeout` | float | `3.0` | Timeout for DNS resolution (seconds) |+| `http_timeout` | float | `10.0` | Timeout for HTTP requests (seconds) |++### Output Format++Each result is a dict:++```python+{+ "url": "https://docs.superdesign.dev/quickstart",+ "host": "docs.superdesign.dev",+ "source": "homepage+sitemap", # which source(s) found it+ "status": "valid", # valid | not_valid | soft_404+ "head_data": { # if extract_head=True+ "title": "Quickstart",+ "meta": {"description": "..."},+ "link": {...},+ "jsonld": [...]+ },+ "relevance_score": 0.85, # if query provided+}+```++## Practical Examples++### Discover and Crawl Documentation++```python+import asyncio+from crawl4ai import AsyncWebCrawler, DomainMapperConfig, CrawlerRunConfig++async def crawl_all_docs():+ async with AsyncWebCrawler() as crawler:+ # Step 1: Discover all URLs+ pages = await crawler.amap_domain("example.com", DomainMapperConfig(+ source="sitemap+crt+probe+homepage",+ extract_head=True,+ query="documentation tutorial guide",+ ))++ # Step 2: Filter for docs+ doc_urls = [+ p["url"] for p in pages+ if p.get("relevance_score", 0) > 0.3+ ]+ print(f"Found {len(doc_urls)} documentation pages")++ # Step 3: Crawl them+ results = await crawler.arun_many(+ doc_urls[:50],+ config=CrawlerRunConfig(only_text=True)+ )+ for r in results:+ if r.success:+ print(f" Crawled: {r.url}")++asyncio.run(crawl_all_docs())+```++### Security Audit: Find Exposed Services++```python+async def audit_domain():+ async with DomainMapper() as mapper:+ results = await mapper.scan("company.com", DomainMapperConfig(+ source="crt+probe+robots",+ extract_head=True,+ probe_paths=[+ "/openapi.json", "/swagger.json", "/api-docs",+ "/graphql", "/.env", "/debug", "/admin",+ "/phpinfo.php", "/server-status",+ ],+ ))++ # Flag exposed services+ for r in results:+ title = r.get("head_data", {}).get("title", "")+ if any(x in title.lower() for x in ["swagger", "api", "admin", "debug"]):+ print(f" EXPOSED: {r['url']} — {title}")+```++### Compare Subdomains Across a Domain++```python+async def map_infrastructure():+ async with DomainMapper() as mapper:+ results = await mapper.scan("company.com", DomainMapperConfig(+ source="crt+probe",+ extract_head=False,+ ))++ # Group by host+ from collections import defaultdict+ by_host = defaultdict(list)+ for r in results:+ by_host[r["host"]].append(r)++ print(f"Discovered {len(by_host)} hosts:")+ for host, urls in sorted(by_host.items()):+ print(f" {host}: {len(urls)} URLs")+```++## Tips and Best Practices++1. **Start with the default sources** (`sitemap+cc+crt+probe`). Add `wayback`, `robots`, `feed`, and `homepage` if you need maximum coverage.++2. **Use `extract_head=False` for speed** when you just need URL lists. Head extraction makes ~1 HTTP request per URL.++3. **The `query` parameter is powerful** for finding specific content across a large domain without crawling anything.++4. **`probe_paths` is your extensibility hook** — add domain-specific paths you suspect exist.++5. **Rate limiting matters** — `hits_per_sec=10` is respectful. Lower it for smaller sites, raise it for your own infrastructure.++6. **Soft-404 detection is critical for SPAs** — without it, single-page apps flood your results with hundreds of identical shell pages.++## See Also++- [URL Seeding](url-seeding.md) — simpler, single-host URL discovery from sitemaps and Common Crawl+- [Deep Crawling](deep-crawling.md) — follow links dynamically within pages+- [Multi-URL Crawling](../advanced/multi-url-crawling.md) — crawl discovered URLs in bulkdiff --git a/docs/md_v2/core/url-seeding.md b/docs/md_v2/core/url-seeding.mdindex dd0c7c86..7d128234 100644--- a/docs/md_v2/core/url-seeding.md+++ b/docs/md_v2/core/url-seeding.md@@ -1166,4 +1166,8 @@ config = SeedingConfig(6. **Smart TTL Cache**: Sitemap caches with TTL expiry and lastmod validation7. **Automatic Cache Recovery**: Corrupted or incomplete caches are automatically refreshed-Now go forth and seed intelligently!\ No newline at end of file+Now go forth and seed intelligently!++## Need More Coverage?++If you need to discover URLs across an entire domain — including subdomains, hidden services, and pages not listed in any sitemap — check out [Domain Mapping](domain-mapping.md). It combines 8 discovery sources (including Certificate Transparency, Wayback Machine, path probing, and soft-404 detection) to find everything under a domain.\ No newline at end of filediff --git a/mkdocs.yml b/mkdocs.ymlindex 1786863c..cfa010f9 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -29,6 +29,7 @@ nav:- "Deep Crawling": "core/deep-crawling.md"- "Adaptive Crawling": "core/adaptive-crawling.md"- "URL Seeding": "core/url-seeding.md"+ - "Domain Mapping": "core/domain-mapping.md"- "C4A-Script": "core/c4a-script.md"- "Crawler Result": "core/crawler-result.md"- "Browser, Crawler & LLM Config": "core/browser-crawler-config.md"diff --git a/tests/adversarial/test_domain_mapper_adversarial.py b/tests/adversarial/test_domain_mapper_adversarial.pynew file mode 100644index 00000000..14563580--- /dev/null+++ b/tests/adversarial/test_domain_mapper_adversarial.py@@ -0,0 +1,136 @@+"""Adversarial tests for DomainMapper — edge cases, failures, tough scenarios."""+import asyncio+import pytest+import pytest_asyncio+from crawl4ai import DomainMapper, DomainMapperConfig+++pytestmark = pytest.mark.network+++@pytest_asyncio.fixture+async def mapper():+ async with DomainMapper() as m:+ yield m+++class TestDomainMapperAdversarial:++ @pytest.mark.asyncio+ async def test_nonexistent_domain(self, mapper):+ """Domain that doesn't exist should return empty, not crash."""+ config = DomainMapperConfig(+ source="sitemap+probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("thiswillneverexist12345678.dev", config)+ assert results == []++ @pytest.mark.asyncio+ async def test_invalid_source(self, mapper):+ """Invalid source should raise ValueError."""+ config = DomainMapperConfig(source="sitemap+bogus")+ with pytest.raises(ValueError, match="Invalid source"):+ await mapper.scan("example.com", config)++ @pytest.mark.asyncio+ async def test_empty_domain(self, mapper):+ """Empty domain string should not crash."""+ config = DomainMapperConfig(+ source="probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("", config)+ assert isinstance(results, list)++ @pytest.mark.asyncio+ async def test_domain_with_scheme(self, mapper):+ """Domain with https:// prefix should be handled."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ verbose=False,+ max_urls=5,+ )+ results = await mapper.scan("https://docs.crawl4ai.com", config)+ assert len(results) >= 1++ @pytest.mark.asyncio+ async def test_soft_404_filtering_spa(self, mapper):+ """SPA sites (app.superdesign.dev) should have soft-404s filtered."""+ config = DomainMapperConfig(+ source="probe",+ extract_head=False,+ soft_404_detection=True,+ verbose=False,+ )+ results = await mapper.scan("app.superdesign.dev", config)+ # All probed paths on this SPA should be filtered as soft-404s+ # (the site returns 200 for every path with the same shell)+ probe_urls = [r for r in results if r["source"] == "probe"]+ assert len(probe_urls) == 0, \+ f"Expected 0 valid probe URLs on SPA, got {len(probe_urls)}: {[r['url'] for r in probe_urls]}"++ @pytest.mark.asyncio+ async def test_rate_limiting(self, mapper):+ """hits_per_sec=2 should not crash."""+ config = DomainMapperConfig(+ source="probe",+ extract_head=False,+ hits_per_sec=2,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert isinstance(results, list)++ @pytest.mark.asyncio+ async def test_unicode_in_results(self, mapper):+ """Results should handle unicode URLs gracefully."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ for r in results:+ assert isinstance(r["url"], str)++ @pytest.mark.asyncio+ async def test_config_clone(self):+ """DomainMapperConfig.clone() should work."""+ config = DomainMapperConfig(source="sitemap", max_urls=10)+ cloned = config.clone(max_urls=20, force=True)+ assert cloned.max_urls == 20+ assert cloned.force is True+ assert cloned.source == "sitemap" # inherited++ @pytest.mark.asyncio+ async def test_concurrent_host_scanning(self, mapper):+ """Multiple hosts scanned in parallel should not race."""+ config = DomainMapperConfig(+ source="sitemap+crt+probe",+ extract_head=False,+ concurrency=20,+ verbose=False,+ force=True,+ )+ results = await mapper.scan("superdesign.dev", config)+ # Verify no duplicate URLs in results+ urls = [r["url"] for r in results]+ # Normalized dedup should prevent exact duplicates+ assert isinstance(results, list)+ assert len(results) > 0++ @pytest.mark.asyncio+ async def test_probe_without_crt(self, mapper):+ """source='probe' alone should still work (just scans base domain)."""+ config = DomainMapperConfig(+ source="probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ # Should find at least / and /docs+ assert len(results) >= 1diff --git a/tests/integration/test_domain_mapper_e2e.py b/tests/integration/test_domain_mapper_e2e.pynew file mode 100644index 00000000..9b248cff--- /dev/null+++ b/tests/integration/test_domain_mapper_e2e.py@@ -0,0 +1,138 @@+"""Integration tests for DomainMapper — hits real endpoints."""+import asyncio+import pytest+import pytest_asyncio+from crawl4ai import DomainMapper, DomainMapperConfig+++pytestmark = pytest.mark.network+++@pytest_asyncio.fixture+async def mapper():+ async with DomainMapper() as m:+ yield m+++class TestDomainMapperE2E:++ @pytest.mark.asyncio+ async def test_scan_superdesign_dev(self, mapper):+ """Full scan of superdesign.dev should find >=30 URLs across >=5 hosts."""+ config = DomainMapperConfig(+ source="sitemap+cc+crt+probe+robots+homepage",+ extract_head=False,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("superdesign.dev", config)+ hosts = {r["host"] for r in results}++ assert len(results) >= 20, f"Expected >=20 URLs, got {len(results)}"+ assert len(hosts) >= 4, f"Expected >=4 hosts, got {len(hosts)}: {hosts}"+ assert any("docs.superdesign.dev" == r["host"] for r in results), \+ "docs.superdesign.dev should be discovered"++ @pytest.mark.asyncio+ async def test_scan_docs_crawl4ai(self, mapper):+ """docs.crawl4ai.com has a known good sitemap."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert len(results) >= 5, f"Expected >=5 URLs from sitemap, got {len(results)}"+ assert all(r["source"] == "sitemap" for r in results)++ @pytest.mark.asyncio+ async def test_sitemap_only_source(self, mapper):+ """source='sitemap' should not hit CC, crt, or wayback."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("superdesign.dev", config)+ sources = {r["source"] for r in results}+ # Should only have sitemap source+ for s in sources:+ for part in s.split("+"):+ assert part == "sitemap", f"Unexpected source: {part}"++ @pytest.mark.asyncio+ async def test_crt_discovers_subdomains(self, mapper):+ """crt source should discover subdomains for superdesign.dev."""+ config = DomainMapperConfig(+ source="crt+probe",+ extract_head=False,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("superdesign.dev", config)+ hosts = {r["host"] for r in results}+ # crt should find at least docs, app, cloud subdomains+ assert len(hosts) >= 3, f"Expected >=3 hosts, got {len(hosts)}: {hosts}"++ @pytest.mark.asyncio+ async def test_max_urls_limit(self, mapper):+ """max_urls should cap results."""+ config = DomainMapperConfig(+ source="sitemap+crt+probe",+ extract_head=False,+ max_urls=10,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("superdesign.dev", config)+ assert len(results) <= 10, f"Expected <=10 URLs, got {len(results)}"++ @pytest.mark.asyncio+ async def test_source_attribution(self, mapper):+ """Each result should have a source field."""+ config = DomainMapperConfig(+ source="sitemap+probe",+ extract_head=False,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ for r in results:+ assert "source" in r+ assert r["source"], "Source should not be empty"+ assert "host" in r+ assert "url" in r++ @pytest.mark.asyncio+ async def test_head_extraction(self, mapper):+ """extract_head=True should populate head_data with titles."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=True,+ max_urls=5,+ force=True,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ has_title = any(r.get("head_data", {}).get("title") for r in results)+ assert has_title, "At least one result should have a title in head_data"++ @pytest.mark.asyncio+ async def test_crawler_integration(self):+ """Test amap_domain() on AsyncWebCrawler works."""+ from crawl4ai import AsyncWebCrawler+ async with AsyncWebCrawler() as crawler:+ results = await crawler.amap_domain(+ "docs.crawl4ai.com",+ DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ force=True,+ verbose=False,+ max_urls=5,+ ),+ )+ assert len(results) >= 1+ assert all("url" in r for r in results)diff --git a/tests/regression/test_reg_domain_mapper.py b/tests/regression/test_reg_domain_mapper.pynew file mode 100644index 00000000..bc028a42--- /dev/null+++ b/tests/regression/test_reg_domain_mapper.py@@ -0,0 +1,270 @@+"""+Crawl4AI Regression Tests - DomainMapper++Tests DomainMapper functionality: host discovery, soft-404 detection,+multi-source scanning, post-processing, and crawler integration.++All network tests use real endpoints.+"""++import pytest+import pytest_asyncio+from crawl4ai import DomainMapper, DomainMapperConfig, AsyncWebCrawler+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++@pytest_asyncio.fixture+async def mapper():+ async with DomainMapper() as m:+ yield m+++# ---------------------------------------------------------------------------+# Basic scan tests+# ---------------------------------------------------------------------------++async def test_basic_scan(mapper):+ """Scan a domain with sitemaps and get results."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert len(results) >= 1, "Should find at least 1 URL from sitemap"+ assert all("url" in r for r in results)+ assert all("host" in r for r in results)+ assert all("source" in r for r in results)+++async def test_scan_with_head_extraction(mapper):+ """Head extraction should populate title and meta."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=True,+ max_urls=3,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert len(results) >= 1+ has_title = any(r.get("head_data", {}).get("title") for r in results)+ assert has_title, "At least one result should have a title"+++# ---------------------------------------------------------------------------+# Host discovery tests+# ---------------------------------------------------------------------------++async def test_crt_subdomain_discovery(mapper):+ """crt.sh should discover subdomains."""+ config = DomainMapperConfig(+ source="crt+probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("superdesign.dev", config)+ hosts = {r["host"] for r in results}+ assert len(hosts) >= 3, f"Expected >=3 hosts via crt, got {len(hosts)}: {hosts}"+++async def test_dns_subdomain_guessing(mapper):+ """DNS guessing should find common subdomains."""+ hosts = await mapper._guess_subdomains("crawl4ai.com", ["docs", "www", "api"], DomainMapperConfig())+ # docs.crawl4ai.com should resolve+ assert "docs.crawl4ai.com" in hosts+++# ---------------------------------------------------------------------------+# Soft-404 detection tests+# ---------------------------------------------------------------------------++async def test_soft_404_detection(mapper):+ """SPA site should be detected as soft-404."""+ fp = await mapper._fingerprint_soft_404("app.superdesign.dev", DomainMapperConfig())+ assert fp is not None+ assert fp.status_code == 200, "SPA should return 200 for nonexistent paths"+ assert fp.title is not None, "Should capture the SPA shell title"+++async def test_soft_404_filters_probes(mapper):+ """Probing an SPA with soft-404 enabled should filter all paths."""+ config = DomainMapperConfig(+ source="probe",+ soft_404_detection=True,+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("app.superdesign.dev", config)+ probe_urls = [r for r in results if r["source"] == "probe"]+ assert len(probe_urls) == 0, "All probe paths on SPA should be soft-404 filtered"+++# ---------------------------------------------------------------------------+# Source isolation tests+# ---------------------------------------------------------------------------++async def test_sitemap_only_no_cross_contamination(mapper):+ """source='sitemap' should only produce sitemap-sourced results."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ for r in results:+ for part in r["source"].split("+"):+ assert part == "sitemap", f"Unexpected source: {part}"+++async def test_probe_only(mapper):+ """source='probe' should work standalone."""+ config = DomainMapperConfig(+ source="probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert isinstance(results, list)+ assert len(results) >= 1+++# ---------------------------------------------------------------------------+# Post-processing tests+# ---------------------------------------------------------------------------++async def test_max_urls_respected(mapper):+ """max_urls should cap results."""+ config = DomainMapperConfig(+ source="sitemap+probe",+ extract_head=False,+ max_urls=5,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ assert len(results) <= 5+++async def test_nonsense_filter_removes_assets(mapper):+ """Nonsense filter should remove JS/CSS/image URLs."""+ config = DomainMapperConfig(+ source="sitemap+homepage",+ extract_head=False,+ filter_nonsense_urls=True,+ verbose=False,+ )+ results = await mapper.scan("docs.crawl4ai.com", config)+ for r in results:+ url = r["url"].lower()+ assert not url.endswith(".js"), f"JS file should be filtered: {url}"+ assert not url.endswith(".css"), f"CSS file should be filtered: {url}"+ assert not url.endswith(".png"), f"Image should be filtered: {url}"+++# ---------------------------------------------------------------------------+# Error handling tests+# ---------------------------------------------------------------------------++async def test_invalid_source_raises(mapper):+ """Invalid source should raise ValueError."""+ with pytest.raises(ValueError, match="Invalid source"):+ await mapper.scan("example.com", DomainMapperConfig(source="bogus"))+++async def test_nonexistent_domain(mapper):+ """Nonexistent domain should return empty list, not crash."""+ config = DomainMapperConfig(+ source="sitemap+probe",+ extract_head=False,+ verbose=False,+ )+ results = await mapper.scan("thiswillneverexist99999.dev", config)+ assert results == []+++async def test_domain_with_scheme_stripped(mapper):+ """Domain with https:// prefix should work."""+ config = DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ max_urls=3,+ verbose=False,+ )+ results = await mapper.scan("https://docs.crawl4ai.com", config)+ assert len(results) >= 1+++# ---------------------------------------------------------------------------+# Crawler integration tests+# ---------------------------------------------------------------------------++async def test_amap_domain_on_crawler():+ """AsyncWebCrawler.amap_domain() should work end-to-end."""+ async with AsyncWebCrawler() as crawler:+ results = await crawler.amap_domain(+ "docs.crawl4ai.com",+ DomainMapperConfig(+ source="sitemap",+ extract_head=False,+ max_urls=5,+ verbose=False,+ ),+ )+ assert len(results) >= 1+ assert all("url" in r for r in results)+++# ---------------------------------------------------------------------------+# Config tests+# ---------------------------------------------------------------------------++async def test_config_clone():+ """DomainMapperConfig.clone() should produce correct copies."""+ config = DomainMapperConfig(source="sitemap", max_urls=10, verbose=True)+ cloned = config.clone(max_urls=20, force=True)+ assert cloned.max_urls == 20+ assert cloned.force is True+ assert cloned.source == "sitemap"+ assert cloned.verbose is True+++async def test_config_from_kwargs():+ """DomainMapperConfig.from_kwargs() should work."""+ config = DomainMapperConfig.from_kwargs({+ "source": "crt+probe",+ "max_urls": 50,+ })+ assert config.source == "crt+probe"+ assert config.max_urls == 50+ assert config.extract_head is True # defaultdiff --git a/tests/unit/test_domain_mapper_unit.py b/tests/unit/test_domain_mapper_unit.pynew file mode 100644index 00000000..74c92d4e--- /dev/null+++ b/tests/unit/test_domain_mapper_unit.py@@ -0,0 +1,406 @@+"""Unit tests for DomainMapper: soft-404, robots.txt, feeds, normalization, nonsense filter."""+import asyncio+import hashlib+import pytest+from unittest.mock import AsyncMock, MagicMock, patch+from crawl4ai.domain_mapper import (+ DomainMapper,+ Soft404Fingerprint,+ _NONSENSE_SUFFIXES,+ _ASSET_EXTENSIONS,+)+++# ════════════════════════════════════════════════════════════════════════+# Soft-404 Detection+# ════════════════════════════════════════════════════════════════════════++class TestSoft404Detection:++ def test_is_soft_404_title_match(self):+ mapper = DomainMapper.__new__(DomainMapper)+ fp = Soft404Fingerprint(+ status_code=200, title="Page Not Found",+ content_length=1234, body_hash="abc123",+ )+ body = b"<html><title>Page Not Found</title><body>Oops</body></html>"+ assert mapper._is_soft_404(200, body, fp) is True++ def test_is_soft_404_hash_match(self):+ mapper = DomainMapper.__new__(DomainMapper)+ body = b"<html><title>Different Title</title><body>Error content</body></html>"+ body_hash = hashlib.md5(body[:2048]).hexdigest()+ fp = Soft404Fingerprint(+ status_code=200, title="Other Title",+ content_length=len(body), body_hash=body_hash,+ )+ assert mapper._is_soft_404(200, body, fp) is True++ def test_is_soft_404_real_404(self):+ mapper = DomainMapper.__new__(DomainMapper)+ fp = Soft404Fingerprint(+ status_code=200, title="Not Found",+ content_length=100, body_hash="abc",+ )+ body = b"<html><title>Not Found</title></html>"+ # Real 404 status — NOT a soft-404+ assert mapper._is_soft_404(404, body, fp) is False++ def test_is_soft_404_no_fingerprint(self):+ mapper = DomainMapper.__new__(DomainMapper)+ body = b"<html><title>Anything</title></html>"+ assert mapper._is_soft_404(200, body, None) is False++ def test_is_soft_404_different_content(self):+ mapper = DomainMapper.__new__(DomainMapper)+ fp = Soft404Fingerprint(+ status_code=200, title="Not Found",+ content_length=100, body_hash="abc123",+ )+ body = b"<html><title>Real Page</title><body>Actual content here</body></html>"+ assert mapper._is_soft_404(200, body, fp) is False++ def test_is_soft_404_no_title_in_body(self):+ mapper = DomainMapper.__new__(DomainMapper)+ fp = Soft404Fingerprint(+ status_code=200, title="Not Found",+ content_length=100, body_hash="abc123",+ )+ body = b"<html><body>No title tag</body></html>"+ assert mapper._is_soft_404(200, body, fp) is False+++# ════════════════════════════════════════════════════════════════════════+# robots.txt Parsing+# ════════════════════════════════════════════════════════════════════════++class TestRobotsTxtParsing:++ @pytest.mark.asyncio+ async def test_parse_sitemap_directives(self):+ robots_text = (+ "User-agent: *\n"+ "Disallow: /private/\n"+ "Sitemap: https://example.com/sitemap.xml\n"+ "Sitemap: https://example.com/sitemap-posts.xml\n"+ )+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.text = robots_text+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ config = DomainMapperConfig()++ sitemap_urls, disallow_paths = await mapper._scan_robots_txt("example.com", config)+ assert len(sitemap_urls) == 2+ assert "https://example.com/sitemap.xml" in sitemap_urls+ assert "/private/" in disallow_paths++ @pytest.mark.asyncio+ async def test_parse_disallow_ignores_wildcards(self):+ robots_text = (+ "User-agent: *\n"+ "Disallow: /admin/\n"+ "Disallow: /search?*\n"+ "Disallow: /\n"+ "Allow: /public/\n"+ )+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.text = robots_text+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ config = DomainMapperConfig()++ _, paths = await mapper._scan_robots_txt("example.com", config)+ assert "/admin/" in paths+ assert "/public/" in paths+ # Wildcards should be skipped+ assert "/search?*" not in paths+ # Single "/" is too short (len <= 1)+ assert "/" not in paths++ @pytest.mark.asyncio+ async def test_empty_robots(self):+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 404+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ config = DomainMapperConfig()++ sitemap_urls, paths = await mapper._scan_robots_txt("example.com", config)+ assert sitemap_urls == []+ assert paths == []+++# ════════════════════════════════════════════════════════════════════════+# Feed Parsing+# ════════════════════════════════════════════════════════════════════════++class TestFeedParsing:++ def test_parse_rss_feed(self):+ rss = """<?xml version="1.0" encoding="UTF-8"?>+ <rss version="2.0">+ <channel>+ <item><link>https://example.com/post-1</link></item>+ <item><link>https://example.com/post-2</link></item>+ </channel>+ </rss>"""+ mapper = DomainMapper.__new__(DomainMapper)+ urls = mapper._parse_feed_xml(rss, "https://example.com/feed")+ assert len(urls) == 2+ assert "https://example.com/post-1" in urls+ assert "https://example.com/post-2" in urls++ def test_parse_atom_feed(self):+ atom = """<?xml version="1.0" encoding="UTF-8"?>+ <feed xmlns="http://www.w3.org/2005/Atom">+ <entry>+ <link href="https://example.com/entry-1" rel="alternate"/>+ </entry>+ <entry>+ <link href="https://example.com/entry-2"/>+ </entry>+ </feed>"""+ mapper = DomainMapper.__new__(DomainMapper)+ urls = mapper._parse_feed_xml(atom, "https://example.com/atom.xml")+ assert len(urls) == 2+ assert "https://example.com/entry-1" in urls++ def test_parse_rss_guid_fallback(self):+ rss = """<?xml version="1.0"?>+ <rss version="2.0">+ <channel>+ <item>+ <guid isPermaLink="true">https://example.com/guid-post</guid>+ </item>+ </channel>+ </rss>"""+ mapper = DomainMapper.__new__(DomainMapper)+ urls = mapper._parse_feed_xml(rss, "https://example.com/feed")+ assert "https://example.com/guid-post" in urls++ def test_malformed_feed(self):+ mapper = DomainMapper.__new__(DomainMapper)+ urls = mapper._parse_feed_xml("not xml at all <><>", "https://example.com/feed")+ assert urls == []+++# ════════════════════════════════════════════════════════════════════════+# URL Normalization & Dedup+# ════════════════════════════════════════════════════════════════════════++class TestNormalizationDedup:++ def test_trailing_slash_dedup(self):+ mapper = DomainMapper.__new__(DomainMapper)+ results = [+ {"url": "https://example.com/about", "host": "example.com", "source": "sitemap", "status": "valid", "head_data": {}},+ {"url": "https://example.com/about/", "host": "example.com", "source": "probe", "status": "valid", "head_data": {}},+ ]+ deduped = mapper._normalize_and_dedup(results, "example.com")+ assert len(deduped) == 1+ assert "probe" in deduped[0]["source"] or "sitemap" in deduped[0]["source"]++ def test_source_merging(self):+ mapper = DomainMapper.__new__(DomainMapper)+ results = [+ {"url": "https://example.com/page", "host": "example.com", "source": "sitemap", "status": "valid", "head_data": {}},+ {"url": "https://example.com/page", "host": "example.com", "source": "homepage", "status": "valid", "head_data": {}},+ ]+ deduped = mapper._normalize_and_dedup(results, "example.com")+ assert len(deduped) == 1+ sources = set(deduped[0]["source"].split("+"))+ assert "sitemap" in sources+ assert "homepage" in sources+++# ════════════════════════════════════════════════════════════════════════+# Nonsense Filter+# ════════════════════════════════════════════════════════════════════════++class TestNonsenseFilter:++ def test_filters_robots_txt(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/robots.txt") is True++ def test_filters_sitemap_xml(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/sitemap.xml") is True++ def test_filters_js_assets(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/app.bundle.js") is True++ def test_filters_css_assets(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/style.css") is True++ def test_filters_images(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/logo.png") is True+ assert mapper._is_nonsense("https://example.com/photo.jpg") is True++ def test_filters_next_js_chunks(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/_next/static/chunks/main.js") is True++ def test_filters_wayback_garbage(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/%5Cn-") is True+ assert mapper._is_nonsense("https://example.com/%5CnJoin") is True++ def test_keeps_login(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/login") is False++ def test_keeps_dashboard(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/dashboard") is False++ def test_keeps_docs(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/docs") is False++ def test_keeps_api_docs(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/api-docs") is False++ def test_filters_dotfiles(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/.env") is True+ assert mapper._is_nonsense("https://example.com/.git/config") is True++ def test_filters_fonts(self):+ mapper = DomainMapper.__new__(DomainMapper)+ assert mapper._is_nonsense("https://example.com/fonts/arial.woff2") is True+++# ════════════════════════════════════════════════════════════════════════+# crt.sh Response Parsing+# ════════════════════════════════════════════════════════════════════════++class TestCrtShParsing:++ @pytest.mark.asyncio+ async def test_parse_crt_response(self):+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = [+ {"common_name": "example.com", "name_value": "example.com"},+ {"common_name": "docs.example.com", "name_value": "docs.example.com\napi.example.com"},+ {"common_name": "*.example.com", "name_value": "*.example.com"},+ ]+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ hosts = await mapper._discover_via_crt("example.com", DomainMapperConfig())+ assert "example.com" in hosts+ assert "docs.example.com" in hosts+ assert "api.example.com" in hosts+ # Wildcards should be resolved to base+ assert "*.example.com" not in hosts++ @pytest.mark.asyncio+ async def test_crt_filters_unrelated_domains(self):+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = [+ {"common_name": "example.com", "name_value": "example.com"},+ {"common_name": "evil.com", "name_value": "evil.com"},+ ]+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ hosts = await mapper._discover_via_crt("example.com", DomainMapperConfig())+ assert "example.com" in hosts+ assert "evil.com" not in hosts++ @pytest.mark.asyncio+ async def test_crt_handles_failure(self):+ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ mapper.client.get = AsyncMock(side_effect=Exception("timeout"))++ from crawl4ai.async_configs import DomainMapperConfig+ hosts = await mapper._discover_via_crt("example.com", DomainMapperConfig())+ assert hosts == set()+++# ════════════════════════════════════════════════════════════════════════+# Homepage Link Extraction+# ════════════════════════════════════════════════════════════════════════++class TestHomepageLinkExtraction:++ @pytest.mark.asyncio+ async def test_extract_internal_links(self):+ html = """<html>+ <head><title>Test</title></head>+ <body>+ <a href="/about">About</a>+ <a href="/blog">Blog</a>+ <a href="https://external.com/page">External</a>+ </body></html>"""++ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.text = html+ resp.url = "https://example.com/"+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ urls = await mapper._scan_homepage("example.com", "example.com", DomainMapperConfig())+ # Should have internal links, not external+ assert any("/about" in u for u in urls)+ assert any("/blog" in u for u in urls)+ assert not any("external.com" in u for u in urls)++ @pytest.mark.asyncio+ async def test_extract_link_tags(self):+ html = """<html>+ <head>+ <title>Test</title>+ <link rel="alternate" hreflang="es" href="/es/">+ <link rel="preload" href="/features">+ </head>+ <body><a href="/page">Link</a></body></html>"""++ mapper = DomainMapper.__new__(DomainMapper)+ mapper.logger = None+ mapper.client = AsyncMock()+ resp = MagicMock()+ resp.status_code = 200+ resp.text = html+ resp.url = "https://example.com/"+ mapper.client.get = AsyncMock(return_value=resp)++ from crawl4ai.async_configs import DomainMapperConfig+ urls = await mapper._scan_homepage("example.com", "example.com", DomainMapperConfig())+ # Should include link tags+ assert any("/es/" in u for u in urls)+ assert any("/features" in u for u in urls)