Build robots.txt vs meta robots conflict detector.
- User
Build robots.txt vs meta robots conflict detector.
Assistant
Build robots.txt vs meta robots conflict detector.
The user wants a tool to detect conflicts between robots.txt and meta robots tags (specifically X-Robots-Tag HTTP headers and HTML tags).
1. Understand the Goal:
* Input: A URL (or a list of URLs).
* Mechanism:
* Fetch the URL.
* Check robots.txt rules for that User-Agent (usually * or Googlebot).
* Check the HTML <head> for <meta name="robots" ...>.
* Check the HTTP headers for X-Robots-Tag.
* Conflict Detection Logic:
* Case 1: Crawlability vs. Indexability.
* robots.txt blocks crawling (Disallow).
* Meta/Header allows indexing (Index, Follow) or simply doesn't block it.
* Result: Google might still index the URL (via links) but can't crawl content. This is often a "No-Index" via proxy, but technically a conflict of intent. A "Soft 404" or "URL-only" result risk.
* Case 2: Mixed Signals (The "noindex" trap).
* robots.txt allows crawling (Allow).
* Meta/Header says noindex.
* Result: This works as intended (page drops from index), but if you block it in robots.txt later, Google can't see the noindex tag, leading to Case 1.
* Wait, is this a conflict? Strictly speaking, this is the correct way to de-index. Allow in txt + Noindex in meta = Correct implementation.
* Case 3: The actual Conflict.
* robots.txt: Disallow
* Meta/Header: noindex
* Result: Google can't crawl to see the noindex. It might remain indexed (referenced by external links). This is a major SEO issue.
* Also: robots.txt: Disallow vs Meta: index (Same issue).
* **Refined Definition of Conflict for the Tool:**
* **Status 1 (The "Hidden Noindex"):** `robots.txt` blocks access (Disallow) AND (Meta/Header is `noindex` OR `nofollow`). *Reason:* Search engines can't see the `noindex` directive, so they might keep indexing the URL based on external signals.
* **Status 2 (The "Wasted Crawl"):** `robots.txt` blocks access (Disallow) AND Meta/Header is effectively `index`. *Reason:* The bot is told "don't visit" but if it finds a link, it might index the URL without content.
2. Tool Architecture: * Language: Python is best for this (requests, beautifulsoup, robotexclusionrulesparser or re). * Interface: Streamlit or a CLI. Streamlit is more user-friendly for a "builder" request.
3. Implementation Steps:
* Step 1: Robots.txt Parser. Need a way to parse the rules.
* Standard library urllib.robotparser is good enough for basic checks.
* Need to fetch domain.com/robots.txt.
* Step 2: Content Fetcher.
* Get the specific URL.
* Extract Headers (X-Robots-Tag).
* Parse HTML (<meta name="robots">).
* Step 3: Logic Engine.
* Check if URL is blocked by robots.txt.
* Check directives in Meta/Header (noindex, nofollow, noarchive, etc.).
* Compare.
4. Code Structure (Python):
streamlit, requests, bs4, urllib.robotparser, urllib.parse.get_robots_status:
RobotFileParser.can_fetch(user_agent, url).get_page_directives:
X-Robots-Tag header.<meta name="robots">.analyze_conflict:
is_blocked_by_txt, meta_directives, header_directives.is_blocked_by_txt is False: No conflict (Bot can read page and obey meta tags).is_blocked_by_txt is True:
noindex: CONFLICT! (Bot can't see the noindex tag).index (or is absent): Warning (Page might be indexed without content).5. Refining the Streamlit UI: * Title. * Input box for URL. * "Analyze" button. * Output section: * Robots.txt Raw snippet (optional). * Meta Tag detected. * Header detected. * Verdict (Big Red/Green text).
6. Drafting the Code (Mental or Scratchpad): * Handling User Agents: Hardcode '' or let user select? Let's start with 'Googlebot' as default, maybe allow input. For simplicity in a "demo" tool, '' or 'Googlebot' is standard. Let's stick to '*'. * Edge Cases: * Redirects (follow them). * 404s (handle gracefully). * Invalid URLs.
7. Writing the specific implementation:
* *Robots Parser:* `urllib.robotparser.RobotFileParser`.
* *Meta extraction:* `soup.find('meta', attrs={'name': 'robots'})`.
* *Header extraction:* `response.headers.get('X-Robots-Tag')`.
* *The Conflict Logic:*
* **Scenario A:** `robots.txt` = Disallow, Meta = `noindex`.
* *Explanation:* "Crawl blocked, but 'noindex' is invisible to Google. Google might index the URL based on link equity."
* **Scenario B:** `robots.txt` = Allow, Meta = `noindex`.
* *Verdict:* Safe (No conflict). This is how you de-index properly.
* **Scenario C:** `robots.txt` = Allow, Meta = `index`.
* *Verdict:* Safe.
8. Final Polish:
* Make it look nice with emojis.
* Add a requirement list (requirements.txt).
9. Self-Correction/Refinement during thought process:
* Initial thought: Should I write a full web scraper?
* Correction: No, keep it simple. One URL at a time is enough for a logical demo.
* Nuance: X-Robots-Tag can be in the response headers. I must check both HTML meta and HTTP headers.
10. Output Generation:
* Provide the Python code.
* Explain how it works.
* Provide requirements.txt.
* Instructions to run.
(Self-Correction on Logic):
What if X-Robots-Tag says noindex and robots.txt allows it? That's fine.
What if robots.txt disallows it and there are no meta tags? That's fine (URL only result), but technically a "risk" if the user wanted it hidden.
I will define "Conflict" strictly as: Blocking crawling via robots.txt while simultaneously trying to control indexing via Meta/Headers. This renders the Meta/Header directives useless because the crawler stops reading at robots.txt.
Let's build the tool.
Core Logic:
robots.txt check: Is can_fetch False?noindex (in meta or header)?can_fetch is False AND noindex is present.UI:
Let's write the code.
Here is a complete Python tool to detect conflicts between robots.txt and Meta Robots/X-Robots-Tags.
A conflict occurs when robots.txt blocks a crawler (Disallow) but the page-level directives (Meta Tag or X-Robots-Tag) attempt to control indexing (e.g., noindex).
Why is this a conflict?
If robots.txt blocks the crawler, the crawler cannot visit the page to see the noindex tag. Consequently, the search engine may still index the URL (showing it as a "blank" result or "URL only") because it is allowed to reference the link but not allowed to read the "keep out" sign.
You will need Python installed and the following libraries:
pip install requests beautifulsoup4
Save this code as detector.py.
python detector.py
The "Crawl Block" Conflict (Most Common):
robots.txt says Disallow: /private/ and the page /private/page.html has <meta name="robots" content="noindex">.noindex, it flags a Critical Conflict.noindex because it is disallowed. It may index the URL based on external links without content (a "soft 404").The "Header" Conflict:
X-Robots-Tag: noindex in the HTTP headers instead of HTML meta tags.If you are building this into a larger system (like a CI/CD pipeline), consider adding these checks:
site: check: If you detect a conflict, automatically query Google to see if the URL is actually indexed.robots.txt, that is also a "Conflict of Intent" (you are asking Google to look at it while slamming the door).import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
import sys
class RobotsConflictDetector:
def __init__(self, target_url, user_agent="*"):
self.target_url = target_url
self.user_agent = user_agent
self.parsed_url = urlparse(target_url)
self.base_url = f"{self.parsed_url.scheme}://{self.parsed_url.netloc}"
# State
self.robots_txt_rules = []
self.is_blocked_by_txt = False
self.meta_directives = []
self.x_robots_directives = []
self.conflicts = []
def fetch_url(self, url):
try:
# We use a verify=False for testing environments with SSL issues,
# ideally set to True in production.
headers = {'User-Agent': self.user_agent}
response = requests.get(url, headers=headers, timeout=10, verify=False)
return response
except Exception as e:
print(f"❌ Error fetching {url}: {e}")
return None
def check_robots_txt(self):
"""Parses robots.txt to see if the target URL is blocked for the current UA."""
robots_url = f"{self.base_url}/robots.txt"
print(f"🔍 Checking robots.txt at: {robots_url}")
response = self.fetch_url(robots_url)
if not response or response.status_code != 200:
print(" ⚠️ No robots.txt found or inaccessible.")
return
lines = response.text.splitlines()
# Very simple robots.txt parser logic
relevant_block = False
for line in lines:
line = line.strip()
# Check User-Agent relevance
if line.lower().startswith('user-agent:'):
ua = line.split(':', 1)[1].strip()
# If the line is '*' or matches our specific UA, we start listening
if ua == '*' or ua.lower() == self.user_agent.lower():
relevant_block = True
else:
relevant_block = False
continue
# Check Disallow rules
if relevant_block and line.lower().startswith('disallow:'):
path = line.split(':', 1)[1].strip()
if not path: continue # Empty disallow means Allow all
# Check if target URL path starts with the disallow path
if self.parsed_url.path.startswith(path):
self.is_blocked_by_txt = True
self.robots_txt_rules.append(f"Blocked by rule: Disallow: {path}")
print(f" 🚫 Blocked by robots.txt rule: {path}")
if not self.is_blocked_by_txt:
print(" ✅ Allowed by robots.txt.")
def check_page_directives(self):
"""Checks HTML Meta tags and HTTP Headers for robots directives."""
print(f"🔍 Checking page directives for: {self.target_url}")
response = self.fetch_url(self.target_url)
if not response:
return
# 1. Check X-Robots-Tag Header
x_robots = response.headers.get('X-Robots-Tag', '')
if x_robots:
self.x_robots_directives = [d.strip().lower() for d in x_robots.split(',')]
print(f" 📄 X-Robots-Tag found: {x_robots}")
# 2. Check Meta Robots Tag
# We handle text/html specifically
content_type = response.headers.get('Content-Type', '')
if 'text/html' in content_type:
soup = BeautifulSoup(response.text, 'html.parser')
meta_tag = soup.find('meta', attrs={'name': 'robots'})
if meta_tag and meta_tag.get('content'):
content = meta_tag.get('content')
self.meta_directives = [d.strip().lower() for d in content.split(',')]
print(f" 📄 Meta Robots found: {content}")
def analyze(self):
"""Compares robots.txt status vs page directives."""
print("\n" + "="*40)
print("📊 ANALYSIS REPORT")
print("="*40)
# Case 1: Blocked by TXT but has page directives
if self.is_blocked_by_txt:
has_noindex = 'noindex' in self.meta_directives or 'noindex' in self.x_robots_directives
if has_noindex:
print("🚨 CONFLICT DETECTED: 'Noindex' hidden by Robots.txt")
print(" - Robots.txt blocks the crawler.")
print(" - The page asks to be 'noindexed'.")
print(" - ⚠️ RESULT: Search engines cannot see the 'noindex' command.")
print(" - 🔧 FIX: Remove the URL from robots.txt Disallow list to let crawlers see the noindex tag.")
return
if self.meta_directives or self.x_robots_directives:
print("⚠️ POTENTIAL ISSUE: Directives Hidden by Robots.txt")
print(" - Robots.txt blocks the crawler.")
print(f" - Page contains directives: {self.meta_directives + self.x_robots_directives}")
print(" - ⚠️ RESULT: These directives are ignored because crawlers can't read them.")
return
# Case 2: Not blocked by TXT, checking for standard health
if not self.is_blocked_by_txt:
if 'noindex' in self.meta_directives or 'noindex' in self.x_robots_directives:
print("✅ HEALTHY: Page is crawlable and set to NoIndex.")
print(" - Crawlers can access the page and will obey the 'noindex'.")
elif self.meta_directives or self.x_robots_directives:
print(f"✅ HEALTHY: Page is crawlable with directives: {self.meta_directives + self.x_robots_directives}")
else:
print("✅ HEALTHY: Page is fully crawlable and indexable (Index, Follow).")
if __name__ == "__main__":
# Example Usage
target = input("Enter URL to check: ").strip()
if not target.startswith("http"):
target = "https://" + target
try:
import warnings
warnings.filterwarnings("ignore") # Suppress SSL warnings for local testing
detector = RobotsConflictDetector(target)
detector.check_robots_txt()
detector.check_page_directives()
detector.analyze()
except KeyboardInterrupt:
sys.exit()