#!/usr/bin/env python3 """AI crawler access audit: what each site's robots.txt says to AI crawlers, and what a plain request with each crawler's user agent gets back from the homepage. Standard library only. One robots.txt fetch, one llms.txt fetch and one homepage fetch per user agent, per site, with a pause between requests. Every request identifies itself as nrlc-crawler-access-audit by default. If a site refuses that agent, the refusal is recorded; the script does not retry under another identity. robots.txt decisions are computed from the file this script received. A server can return a different file to a different client, so they are exact for that file, not a guarantee of what each crawler is served. The script never sends another crawler's user-agent string. Usage: python3 ai_crawler_access_audit.py sites.tsv OUTDIR sites.tsv columns: brand, group, url """ import csv, hashlib, html, json, os, re, subprocess, sys, tempfile, time, urllib.parse AUDIT_UA = 'nrlc-crawler-access-audit/1.0 (+https://nrlc.ai/en-us/insights/ai-crawler-access-ai-visibility-vendors/)' BROWSER_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' # robots.txt tokens, with the operator's stated purpose. ROBOT_AGENTS = [ ('GPTBot', 'OpenAI', 'training'), ('OAI-SearchBot', 'OpenAI', 'search'), ('ChatGPT-User', 'OpenAI', 'user_fetch'), ('ClaudeBot', 'Anthropic', 'training'), ('Claude-SearchBot', 'Anthropic', 'search'), ('Claude-User', 'Anthropic', 'user_fetch'), ('PerplexityBot', 'Perplexity', 'search'), ('Perplexity-User', 'Perplexity', 'user_fetch'), ('Google-Extended', 'Google', 'training'), ('Googlebot', 'Google', 'search'), ('Bingbot', 'Microsoft', 'search'), ('Applebot-Extended', 'Apple', 'training'), ('CCBot', 'Common Crawl', 'training'), ('meta-externalagent', 'Meta', 'training'), ('Bytespider', 'ByteDance', 'training'), ] # A made-up content path: stands in for 'an ordinary page on the site' (no site lists it). INNER_PATH = '/nrlc-audit-sample-page/' CHALLENGE_MARKERS = re.compile(r'just a moment\.\.\.|cf-chl|challenge-platform|captcha|attention required|access denied|verify you are human|px-captcha|_incapsula_', re.I) def fetch(url, ua, timeout=25): """One GET through the system curl (modern TLS and HTTP/2, as real crawlers use). Follows redirects. Returns status 0 with the curl error on network or TLS failure.""" with tempfile.TemporaryDirectory() as d: body_p, head_p = os.path.join(d, 'b'), os.path.join(d, 'h') cmd = ['curl', '-s', '-L', '--max-redirs', '10', '--compressed', '--max-time', str(timeout), '-A', ua, '-H', 'Accept: text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.8', '-H', 'Accept-Language: en-US,en;q=0.9', '-o', body_p, '-D', head_p, '-w', '%{http_code} %{url_effective}\n%{errormsg}', url] out = subprocess.run(cmd, capture_output=True, text=True).stdout first, _, err = out.partition('\n') code, _, final = first.partition(' ') body = open(body_p, 'rb').read().decode('utf-8', 'replace') if os.path.exists(body_p) else '' headers = {} if os.path.exists(head_p): # keep only the last response's headers (after redirects) block = re.split(r'\r?\n\r?\n', open(head_p, 'rb').read().decode('latin-1').strip())[-1] for line in block.splitlines()[1:]: if ':' in line: k, v = line.split(':', 1) headers[k.strip()] = v.strip() status = int(code) if code.isdigit() else 0 return {'status': status, 'error': err.strip() if status == 0 else '', 'body': body, 'headers': headers, 'final': final or url} def parse_robots(text): """Groups of (agents, rules) per RFC 9309. Rules are (allow: bool, pattern).""" groups, agents, rules, last_was_agent = [], [], [], False for raw in text.splitlines(): line = raw.split('#', 1)[0].strip() if ':' not in line: continue key, val = (s.strip() for s in line.split(':', 1)) key = key.lower() if key == 'user-agent': if not last_was_agent and agents: groups.append((agents, rules)) agents, rules = [], [] agents.append(val.lower()) last_was_agent = True elif key in ('allow', 'disallow'): last_was_agent = False if agents: rules.append((key == 'allow', val)) else: last_was_agent = False if agents: groups.append((agents, rules)) return groups def rule_matches(pattern, path): if pattern == '': return False rx = re.escape(pattern).replace(r'\*', '.*') if rx.endswith(r'\$'): rx = rx[:-2] + '$' return re.match(rx, path) is not None def group_disallows(groups, agent): token = agent.lower() named = [r for a, r in groups if token in a] or [r for a, r in groups if '*' in a] return sorted({pat for rs in named for allow, pat in rs if not allow and pat}) def robots_decision(groups, agent, path='/'): """RFC 9309: use groups naming the agent (case-insensitive product token), else '*'. Longest matching rule wins; allow wins a tie.""" token = agent.lower() named = [r for a, r in groups if token in a] source = 'named' if not named: named = [r for a, r in groups if '*' in a] source = 'wildcard' if named else 'none' rules = [rule for rs in named for rule in rs] best = None for allow, pat in rules: if rule_matches(pat, path): key = (len(pat), allow) if best is None or key > best[0]: best = (key, allow, pat) if best is None: return 'allowed', source, '' return ('allowed' if best[1] else 'blocked'), source, ('Allow: ' if best[1] else 'Disallow: ') + best[2] def visible_text_len(body): b = re.sub(r'(?is)<(script|style|noscript|template|svg)[^>]*>.*?\1>', ' ', body) b = re.sub(r'(?s)<[^>]+>', ' ', b) return len(re.sub(r'\s+', ' ', html.unescape(b)).strip()) def jsonld_types(body): types = [] for block in re.findall(r'(?is)', body): try: data = json.loads(block.strip()) except Exception: types.append('INVALID') continue stack = [data] while stack: n = stack.pop() if isinstance(n, list): stack.extend(n) elif isinstance(n, dict): t = n.get('@type') if isinstance(t, str): types.append(t) elif isinstance(t, list): types.extend(str(x) for x in t) stack.extend(v for k, v in n.items() if k == '@graph') return types def title_of(body): m = re.search(r'(?is)