Sub topic 15
Testing and troubleshooting both files
This chapter assumes you can write a basic robots.txt and a sitemap, know how Allow, Disallow, * and $ work, and know the sitemap limits (50,000 URLs and 50 MB uncompressed per file). Here you will verify that both files work, and find the cause when they don't.
A testing order that saves time
Most failures sit at the start of the chain. A crawler cannot obey a rule in a file it can't fetch, and it can't use a sitemap it can't parse. Check in this order:
Testing robots.txt
Check the fetch first
Request the file the way a crawler would:
curl -sI https://www.example.com/robots.txtLook at the status line and the Content-Type header.
| Response | What crawlers do (Google's documented behavior) |
|---|---|
| 200 with `text/plain` | Parse and obey the rules. |
| 3xx | Follow a limited number of redirects. After too many, treat the file as missing. |
| 404 or other 4xx (except 429) | Treat the file as absent and crawl everything. |
| 5xx or 429 | Pause crawling for a while, because the rules are unknown. A long-running outage can change this behavior. |
The 404 case catches many sites by surprise. A deploy that deletes robots.txt silently removes all your blocks. A 5xx on that one URL can stall crawling of the whole site.
Also check the size. Google reads only the first 500 KiB and ignores the rest, so rules at the bottom of an oversized file never apply.
Test rules with a script
Python's urllib.robotparser lets you assert expected results in a test suite. It differs from Google's matcher in two ways:
- It applies the first rule that matches, in file order. Google picks the most specific (longest) matching rule.
- It does not support
*or$inside paths.
Order your rules so the stdlib result matches what Google would do:
from urllib.robotparser import RobotFileParser
rules = [
"User-agent: *",
"Allow: /admin/help/",
"Disallow: /admin/",
]
rp = RobotFileParser()
rp.parse(rules)
expectations = {
"https://www.example.com/admin/help/faq": True,
"https://www.example.com/admin/users": False,
"https://www.example.com/blog/": True,
}
for url, expected in expectations.items():
actual = rp.can_fetch("*", url)
status = "ok" if actual == expected else "MISMATCH"
print(f"{status}: {url} allowed={actual}")If you swap the first two rules, the /admin/help/faq line reports MISMATCH. The stdlib then hits Disallow: /admin/ first, while Google would allow the URL.
Common robots.txt problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Whole site blocked after a launch | Staging `Disallow: /` copied to production | Replace the file and re-test the home page. |
| A rule has no effect | Directive misspelled, or placed before any `User-agent` line | Every rule must belong to a group that starts with `User-agent`. |
| A crawler ignores your `*` group | It has its own, more specific group, and only that group applies | Copy the needed rules into the specific group. |
| Rules apply on one host only | `robots.txt` is per protocol, host, and port | Serve a file on each subdomain, and on `http` and `https` if both respond. |
| Blocked page still appears in results | Disallow stops crawling, not indexing | Allow crawling and use `noindex`, as described below. |
| Wrong path blocked | Missing leading `/`, or `Disallow: /search` also matching `/search-tips` | Anchor with a trailing `/` or `$` where needed. |
The "still appears in results" case needs a closer look. If a page has noindex but robots.txt blocks it, the crawler never fetches the page and never sees the noindex. The URL can stay in the index, usually with no description. Search Console reports this as "Indexed, though blocked by robots.txt". To remove the page, allow crawling first, let the crawler see noindex, and re-add the block later if you still want it.
Testing sitemaps
A sitemap can fail in three ways: the fetch fails, the XML is invalid, or the URLs inside are bad. The first two are mechanical. The third is where most real problems are.
What to validate
- The file is well-formed XML in UTF-8, with the
http://www.sitemaps.org/schemas/sitemap/0.9namespace. - Every
locis an absolute URL with a scheme and host, and special characters such as&are escaped as&. - All URLs share the host of the sitemap.
- There are no more than 50,000 URLs and no more than 50 MB uncompressed.
- Every
lastmodis a valid W3C date or datetime. - No listed URL is blocked by
robots.txt.
The script below checks these points offline. Run it as python check_sitemap.py sitemap.xml robots.txt.
import os
import sys
import xml.etree.ElementTree as ET
from datetime import datetime
from urllib.parse import urlparse
from urllib.robotparser import RobotFileParser
NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
MAX_URLS = 50_000
MAX_BYTES = 50 * 1024 * 1024
def check_sitemap(path, robots_lines):
problems = []
if os.path.getsize(path) > MAX_BYTES:
problems.append("file is larger than 50 MB uncompressed")
try:
root = ET.parse(path).getroot()
except ET.ParseError as exc:
return [f"not well-formed XML: {exc}"]
if root.tag != "{%s}urlset" % NS["sm"]:
return [f"unexpected root element: {root.tag}"]
rp = RobotFileParser()
rp.parse(robots_lines)
urls = root.findall("sm:url", NS)
if len(urls) > MAX_URLS:
problems.append(f"{len(urls)} URLs exceeds the 50,000 limit")
seen = set()
host = None
for url in urls:
loc_el = url.find("sm:loc", NS)
loc = (loc_el.text or "").strip() if loc_el is not None else ""
parts = urlparse(loc)
if not parts.scheme or not parts.netloc:
problems.append(f"loc is not an absolute URL: {loc!r}")
continue
host = host or parts.netloc
if parts.netloc != host:
problems.append(f"different host: {loc}")
if loc in seen:
problems.append(f"duplicate: {loc}")
seen.add(loc)
if not rp.can_fetch("*", loc):
problems.append(f"blocked by robots.txt: {loc}")
lastmod = url.find("sm:lastmod", NS)
if lastmod is not None:
value = (lastmod.text or "").strip().replace("Z", "+00:00")
try:
datetime.fromisoformat(value)
except ValueError:
problems.append(f"bad lastmod {value!r} for {loc}")
return problems
if __name__ == "__main__":
sitemap_path, robots_path = sys.argv[1], sys.argv[2]
with open(robots_path, encoding="utf-8") as f:
issues = check_sitemap(sitemap_path, f.read().splitlines())
for issue in issues:
print("PROBLEM:", issue)
print("clean" if not issues else f"{len(issues)} problem(s)")
sys.exit(1 if issues else 0)The robots cross-check uses the stdlib parser, so it has the same wildcard limitation described earlier. It will not catch a URL blocked by a * or $ rule.
An offline check cannot tell you whether a URL returns 200, redirects, or carries noindex. For that, sample live URLs with curl -sI or a crawler such as a site-audit tool. Sitemaps full of redirects, 404s, and noindex pages are the most common quality problem.
Common sitemap problems
| Symptom | Likely cause | Fix |
|---|---|---|
| "Couldn't fetch" or "Sitemap could not be read" | Wrong URL, 404, server error, or the sitemap is blocked by `robots.txt` | Fetch it with `curl -sI` and check the status and the robots rules. |
| Parse error | Unescaped `&`, a stray byte-order mark, a truncated file, or an HTML error page served at the sitemap URL | Generate the file with an XML library, not string concatenation. |
| Many URLs "discovered" but not indexed | A sitemap suggests URLs. It does not guarantee indexing | Check content quality, duplicates, and canonical tags for those URLs. |
| URLs listed that redirect or return errors | The sitemap is stale | Regenerate from live data and list only final, canonical, indexable URLs. |
| `lastmod` is the same on every URL | The generator writes the build time | Use the real content-change date. If it is not trustworthy, crawlers learn to ignore it. |
| Sitemap index rejected | It lists another index, or a child file exceeds the limits | An index may list only sitemap files, not other indexes. Split the children. |
A short troubleshooting checklist
- Fetch
robots.txtand confirm status 200 and a plain-text body. - Test the affected URL against the rules, and for wildcard rules use the search engine's tester.
- Confirm the matching group is the one you expect. A named crawler group replaces
*. - Fetch the sitemap and run the validator.
- Spot-check live URLs for status, redirects, canonical tags, and
noindex. - Use the search console's URL inspection for a single page, and read its reason for exclusion.
Exercise
A page has <meta name="robots" content="noindex"> but still appears in search results. Your robots.txt contains Disallow: /old-offers/, and the page lives at /old-offers/spring.html. Why does the page stay indexed, and what do you change?
Show answer
The Disallow rule stops the crawler from fetching the page, so it never sees the noindex tag, and the URL can stay in the index from links alone. Remove the Disallow rule (or make an exception for that path), let the crawler re-fetch the page and read noindex, and wait until it drops out of the index. After that you can block the path again if you still want to.
Exercise
Your validator script prints "clean", but Search Console says a sitemap URL is "Blocked by robots.txt". The rule is Disallow: /*?ref=. What explains the gap?
Show answer
The stdlib urllib.robotparser does not support * wildcards, so it read /*?ref= as a literal path and allowed every URL. Google's matcher applies the wildcard and blocks any URL containing ?ref=. Remove those URLs from the sitemap (or fix the rule) and verify with the search engine's own robots tester.