Ship a robots rules QA bot: allow/disallow parity, sitemap alignments, and harness tests.
- User
Ship a robots rules QA bot: allow/disallow parity, sitemap alignments, and harness tests.
Assistant
Ship a robots rules QA bot: allow/disallow parity, sitemap alignments, and harness tests.
The user wants a "robots rules QA bot." The key features requested are:
robots.txt and vice versa (checking for blocked resources or indexed pages that shouldn't be).The output should likely be a complete codebase or a well-structured module that implements this logic. Given the constraints of a text response, I'll design a Python-based solution. Python is the standard for this kind of utility (using the urllib.robotparser library and requests for fetching).
Plan:
RobotQA class):
robots.txt.sitemap.xml.* vs Googlebot).robots.txt of two different URLs (e.g., Prod vs. Staging).robots.txt to ensure it's allowed.Drafting the Code (Mental or Scratchpad):
Libraries: urllib.robotparser, requests, xml.etree.ElementTree (for sitemap).
Class RobotsQA:
__init__(base_url)load_robots()check_parity(target_url) (compare self vs target)check_sitemap_alignment() (fetch sitemaps listed in robots, check if URLs are allowed)run_harness(test_cases) (list of tuples: path, user_agent, expected_bool)Refining "Parity": The user mentioned "allow/disallow parity". This usually means:
User-agent: * have the same rules as User-agent: Googlebot?staging.com/robots.txt match prod.com/robots.txt? I will implement the logic to check for discrepancies between the "Global" (*) agent and a specific "Target" agent (like Googlebot), as that's a common SEO mistake.Refining "Harness": Needs to be a simple function where a developer can dump a dictionary of URLs to check.
Step-by-Step Implementation Plan:
urllib.robotparser, requests, xml, difflib (for diffing rules).fetch: HTTP GET.check_sitemap_vs_robots: The alignment check.check_agent_parity: Compare * vs specific agent.run_test_harness: The unit-test style runner.main block showing how to use it.Self-Correction/Edge Cases:
urllib.robotparser is standard but can be slow or strict. It's sufficient for a QA bot.Final Code Structure:
import requests
from urllib.robotparser import RobotFileParser
from urllib.parse import urlparse, urljoin
import xml.etree.ElementTree as ET
from typing import List, Dict, Tuple
class RobotsQABot:
# Initialization and fetching
# 1. Harness Tests (URL -> Allowed?)
# 2. Sitemap Alignment (Sitemap URLs allowed?)
# 3. Parity (Compare User-Agents)
Let's write the code. I will ensure the parity check looks for logical conflicts (e.g. Disallow: /admin for * but Allow: /admin for Googlebot).
Parity definition update: The user likely means "Do the rules match?" or "Are there inconsistencies?". I will implement a check that compares the effective permission for a list of common paths between User Agent * and a specific Bot (like Googlebot).
Let's assemble the solution. This is a complete Python implementation of a Robots.txt QA Bot. It functions as a command-line tool and library that validates allow/disallow parity, checks if sitemap URLs are crawlable, and runs a URL harness test against the current rules.
You will need Python 3 and requests installed.
pip install requests
robot_qa.py)import sys
import time
import requests
from urllib.robotparser import RobotFileParser
from urllib.parse import urlparse, urljoin
import xml.etree.ElementTree as ET
from typing import List, Dict, Tuple, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
class Colors:
"""Helper class for terminal output coloring."""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
class RobotsQABot:
def __init__(self, base_url: str, user_agent: str = "*"):
self.base_url = base_url.rstrip('/')
self.robots_url = f"{self.base_url}/robots.txt"
self.user_agent = user_agent
self.rp = RobotFileParser()
self.raw_content = ""
print(f"{Colors.HEADER}Initializing QA Bot for: {self.base_url}{Colors.ENDC}")
self._load_robots()
def _load_robots(self):
"""Fetches and parses the robots.txt file."""
try:
response = requests.get(self.robots_url, timeout=10)
self.raw_content = response.text
if response.status_code != 200:
raise ConnectionError(f"Status {response.status_code}")
# Populate the standard parser
self.rp.parse(self.raw_content.splitlines())
print(f"{Colors.OKGREEN}✔ Successfully loaded robots.txt{Colors.ENDC}")
except Exception as e:
print(f"{Colors.FAIL}✖ Failed to load robots.txt: {e}{Colors.ENDC}")
sys.exit(1)
# ---------------------------------------------------------
# FEATURE 1: HARNESS TESTS
# ---------------------------------------------------------
def run_harness_tests(self, test_cases: List[Dict[str, str]]):
"""
Runs a suite of specific URL paths against the rules.
test_case format: {'path': '/admin', 'should_access': False}
"""
print(f"\n{Colors.BOLD}--- Running Harness Tests ---{Colors.ENDC}")
failures = 0
for case in test_cases:
path = case['path']
expected = case['should_access']
full_url = f"{self.base_url}{path}"
# Check using standard parser
can_fetch = self.rp.can_fetch(self.user_agent, full_url)
status = "PASS"
color = Colors.OKGREEN
if can_fetch != expected:
status = "FAIL"
color = Colors.FAIL
failures += 1
print(f"[{color}{status}{Colors.ENDC}] Path: {path}")
print(f" Expected: {expected}, Actual: {can_fetch}")
return failures == 0
# ---------------------------------------------------------
# FEATURE 2: SITEMAP ALIGNMENT
# ---------------------------------------------------------
def check_sitemap_alignment(self):
"""
Checks if URLs listed in the sitemap are actually allowed by robots.txt.
"""
print(f"\n{Colors.BOLD}--- Checking Sitemap Alignment ---{Colors.ENDC}")
sitemaps = self._extract_sitemaps_from_robots()
if not sitemaps:
print(f"{Colors.WARNING}No sitemaps found in robots.txt.{Colors.ENDC}")
return
print(f"Found {len(sitemaps)} sitemap(s). Parsing...")
urls_to_check = set()
for sm_url in sitemaps:
urls_to_check.update(self._fetch_sitemap_urls(sm_url))
blocked_count = 0
for url in urls_to_check:
if not self.rp.can_fetch(self.user_agent, url):
print(f"{Colors.FAIL}[MISALIGN]{Colors.ENDC} Sitemap URL blocked by robots.txt: {url}")
blocked_count += 1
if blocked_count == 0:
print(f"{Colors.OKGREEN}✔ All {len(urls_to_check)} sitemap URLs are crawlable.{Colors.ENDC}")
else:
print(f"{Colors.FAIL}✖ Found {blocked_count} blocked URLs in sitemaps.{Colors.ENDC}")
def _extract_sitemaps_from_robots(self) -> List[str]:
return self.rp.site_maps() or []
def _fetch_sitemap_urls(self, sitemap_url: str) -> set:
urls = set()
try:
# Naive XML parsing for standard sitemaps
resp = requests.get(sitemap_url, timeout=10)
root = ET.fromstring(resp.content)
# Handle standard namespace
ns = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
for loc in root.findall('ns:url/ns:loc', ns):
urls.add(loc.text.strip())
# Handle sitemap index files (recursive slightly)
for loc in root.findall('ns:sitemap/ns:loc', ns):
# Logic could recursively fetch, but keeping it simple for QA harness
pass
except Exception as e:
print(f"{Colors.WARNING}Warning: Could not parse sitemap {sitemap_url}: {e}{Colors.ENDC}")
return urls
# ---------------------------------------------------------
# FEATURE 3: ALLOW/DISALLOW PARITY
# ---------------------------------------------------------
def check_agent_parity(self, agents: List[str] = ['*', 'Googlebot', 'Bingbot']):
"""
Checks if specific agents have different access rules compared to '*' (Global).
"""
print(f"\n{Colors.BOLD}--- Checking Rule Parity ---{Colors.ENDC}")
# We need a set of paths to test against. We can extract paths from rules
# or simply test common sensitive paths.
# Here, we extract paths defined in the CURRENT robots.txt to test logic consistency.
paths_to_audit = self._extract_disallowed_paths()
divergences = []
for path in paths_to_audit:
global_access = self.rp.can_fetch('*', f"{self.base_url}{path}")
for agent in agents:
if agent == '*': continue
agent_access = self.rp.can_fetch(agent, f"{self.base_url}{path}")
if global_access != agent_access:
msg = (f"Parity Mismatch on {path}: "
f"User '*' is {'ALLOWED' if global_access else 'BLOCKED'}, "
f"but '{agent}' is {'ALLOWED' if agent_access else 'BLOCKED'}")
divergences.append(msg)
if not divergences:
print(f"{Colors.OKGREEN}✔ No parity discrepancies found among {agents}.{Colors.ENDC}")
else:
for d in divergences:
print(f"{Colors.WARNING}[PARITY]{Colors.ENDC} {d}")
def _extract_disallowed_paths(self) -> set:
"""Parses the raw text to find all explicitly defined paths."""
paths = set()
for line in self.raw_content.splitlines():
line = line.strip()
if line.lower().startswith('disallow:') or line.lower().startswith('allow:'):
parts = line.split(':', 1)
if len(parts) > 1:
path = parts[1].strip()
if path:
paths.add(path)
return paths
# ---------------------------------------------------------
# EXECUTION HARNESS
# ---------------------------------------------------------
if __name__ == "__main__":
# 1. Configure Target
TARGET_SITE = "https://example.com" # Replace with your target
# 2. Define QA Test Harness (URLs and expected outcomes)
HARNESS = [
{'path': '/', 'should_access': True},
{'path': '/admin/login', 'should_access': False},
{'path': '/search', 'should_access': False},
{'path': '/public/assets/style.css', 'should_access': True},
]
# 3. Initialize Bot
bot = RobotsQABot(TARGET_SITE)
# 4. Run Checks
# A. Harness Tests (Unit tests for URLs)
bot.run_harness_tests(HARNESS)
# B. Parity Checks (Do Googlebot and * see the same thing?)
bot.check_agent_parity(agents=['*', 'Googlebot'])
# C. Sitemap Alignment (Are sitemap links blocked?)
bot.check_sitemap_alignment()
robot_qa.py.TARGET_SITE and the HARNESS list at the bottom to match your specific website's routes and expectations.python3 robot_qa.py.run_harness_tests)This allows you to define "Unit Tests" for your routing. You define a path (e.g., /admin) and the expected result (should_access: False). The bot asserts the reality against your expectation. This is critical for preventing accidental indexation of dev/staging environments or private pages.
check_sitemap_alignment)A common SEO error is listing URLs in sitemap.xml that are actually blocked by Disallow rules in robots.txt. The bot fetches the sitemaps defined in your robots file, parses the XML, and checks every URL found against the Robot rules.
check_agent_parity)This detects logic drift. Often, developers block a path for User-agent: * but forget that they previously allowed it specifically for User-agent: Googlebot. This function compares how different user agents interpret the same URL path.