Python for SEO: 6 Short Scripts for Sitemaps, Canonicals, Search Console and AI Crawlers
Python for SEO is a set of scripts that take over the checks you repeat every week: listing the URLs in a sitemap, testing status codes and canonical tags, joining that crawl with Search Console data, grouping queries, and reading robots.txt the way GPTBot or ClaudeBot does. The six scripts below need only the Python standard library.
By Raúl Díaz, founder of Slibur
12 min read

In this article
Leaving out third-party packages is deliberate. Most tutorials start with a long pip install line, and the setup is where many people give up. Every script here uses modules that ship with Python itself (urllib, csv, xml.etree, html.parser and urllib.robotparser), so a fresh install runs them as they are. Each one reads or writes plain CSV, so the output of one step is the input of the next, and any step opens in a spreadsheet.
Before you run anything
Open a terminal and type python3 --version. If it prints a Python 3 version, you are ready. Save each script below as its own file in one folder and run it from that folder, sending the output to a CSV with >.
A few habits keep a script from becoming a nuisance:
- Say who you are. Every script has a
UAline at the top. Put your site or email in it, so a server admin who sees the traffic knows whom to ask. - Go slowly. The scripts pause one second between requests. A large site will take hours, so run the check overnight or start with a sample of URLs.
- Crawl what you own. Point the scripts at your own sites, or at sites whose owners said yes.
- Know the blind spot. urllib downloads the HTML the server sends and runs no JavaScript. If your titles or canonical tags are injected by JavaScript, these checks will report them as missing, and you need a headless browser for those templates. The guide to JavaScript SEO explains when that matters.
If the only question you have is which AI crawlers your robots.txt lets in, the free AI crawler checker answers it without any code. Script 5 shows how to run the same kind of check yourself, on any path.
1. List every URL in your sitemap
The first script takes a sitemap URL and prints every page it lists, with its lastmod date. It follows sitemap index files down to the child sitemaps, decompresses .gz files, and skips any sitemap it has already read, so a sitemap that lists itself cannot loop forever.
import csv, gzip, sys, time, urllib.request
import xml.etree.ElementTree as ET
UA = "my-seo-scripts/1.0 (contact: you@example.com)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
def fetch(url):
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=20) as resp:
data = resp.read()
return gzip.decompress(data) if data[:2] == b"\x1f\x8b" else data
def sitemap_urls(url, seen=None):
seen = set() if seen is None else seen
if url in seen:
return
seen.add(url)
root = ET.fromstring(fetch(url))
if root.tag == NS + "sitemapindex":
for loc in root.iter(NS + "loc"):
time.sleep(1)
yield from sitemap_urls(loc.text.strip(), seen)
else:
for node in root.iter(NS + "url"):
yield node.findtext(NS + "loc", "").strip(), node.findtext(NS + "lastmod", "").strip()
if __name__ == "__main__":
out = csv.writer(sys.stdout)
out.writerow(["url", "lastmod"])
for row in sitemap_urls(sys.argv[1]):
out.writerow(row)
Run it with python3 sitemap_urls.py https://example.com/sitemap.xml > urls.csv.
Why keep lastmod and nothing else? Google's sitemap guidelines (opens in a new tab) say it ignores the priority and changefreq values and uses lastmod only when it is consistently and verifiably accurate. The same page caps a single sitemap at 50MB uncompressed or 50,000 URLs and asks for fully qualified, absolute URLs.
Two quick reads of urls.csv tell you a lot. Sort by lastmod: if thousands of pages share the same date and time, your CMS is probably stamping every URL on each deploy, and that date tells Google nothing. Then count URLs by folder, which surfaces sections that should never have been listed, like tag pages or internal search results. For what belongs in the file in the first place, see the guide to sitemaps and SEO.
2. Check status codes, redirect chains and canonical tags
Script 2 reads urls.csv and requests each URL with urllib's automatic redirects switched off. Following each Location header by hand lets it count the hops. It stops at 10, the default limit Google gives for its own crawlers. For the final page it records the status code, the canonical from the HTML head or from an HTTP Link header, and any noindex in a robots meta tag or an X-Robots-Tag header.
import csv, re, sys, time, urllib.error, urllib.parse, urllib.request
from html.parser import HTMLParser
UA = "my-seo-scripts/1.0 (contact: you@example.com)"
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # follow redirects by hand to count the hops
opener = urllib.request.build_opener(NoRedirect)
class HeadTags(HTMLParser):
def __init__(self):
super().__init__()
self.canonical, self.robots = "", ""
def handle_starttag(self, tag, attrs):
a = {k: (v or "") for k, v in attrs}
if tag == "link" and "canonical" in a.get("rel", "").lower().split():
self.canonical = self.canonical or a.get("href", "").strip()
if tag == "meta" and a.get("name", "").lower() in ("robots", "googlebot"):
self.robots += " " + a.get("content", "").lower()
def same_url(a, b):
a, b = urllib.parse.urlsplit(a), urllib.parse.urlsplit(b)
return (a.scheme, a.netloc.lower(), a.path or "/", a.query) == (b.scheme, b.netloc.lower(), b.path or "/", b.query)
def check(url, max_hops=10):
start, hops = url, 0
while True:
req = urllib.request.Request(url, headers={"User-Agent": UA})
try:
resp = opener.open(req, timeout=15)
except urllib.error.HTTPError as err:
resp = err # 3xx, 4xx and 5xx all arrive here
status, headers = resp.getcode(), resp.headers
location = headers.get("Location")
if 300 <= status < 400 and location and hops < max_hops:
url, hops = urllib.parse.urljoin(url, location), hops + 1
time.sleep(1)
continue
tags = HeadTags()
if status == 200 and "html" in headers.get("Content-Type", ""):
tags.feed(resp.read(500_000).decode("utf-8", "replace"))
header_canon = re.search(r'<([^>]+)>\s*;\s*rel="?canonical"?', headers.get("Link", ""))
canonical = tags.canonical or (header_canon.group(1) if header_canon else "")
robots = tags.robots + " " + headers.get("X-Robots-Tag", "").lower()
if status != 200:
canon_state = ""
elif not canonical:
canon_state = "missing"
elif not urllib.parse.urlsplit(canonical).scheme:
canon_state = "relative"
else:
canon_state = "self" if same_url(canonical, url) else "other"
return [start, status, hops, url, canonical, canon_state, "noindex" in robots]
if __name__ == "__main__":
out = csv.writer(sys.stdout)
out.writerow(["url", "status", "hops", "final_url", "canonical", "canonical_state", "noindex"])
for row in csv.DictReader(open(sys.argv[1], newline="", encoding="utf-8")):
try:
out.writerow(check(row["url"]))
except Exception as err: # DNS failure, timeout, TLS error
out.writerow([row["url"], "error", 0, "", "", "", str(err)[:80]])
time.sleep(1)
Run python3 check_urls.py urls.csv > checks.csv. A row with hops at 10 and a 3xx status is a redirect loop, or a chain long enough that Google may give up on it. Google's documentation on HTTP status codes treats 301 and 308 as strong signals, 302 and 307 as weak ones, and every 4xx error except 429 as a page that does not exist.
The canonical_state column is the one to filter first:
| canonical_state | What it means | What to do |
|---|---|---|
| self | The canonical matches the final URL | Nothing |
| other | The page names a different URL as canonical | Fine for a duplicate, but then it should not be in your sitemap |
| missing | No canonical in the HTML or the headers | Google picks one itself; add the tag to templates that create duplicates |
| relative | The href has no scheme or host | Switch to an absolute URL |
Google's guide to consolidating duplicate URLs (opens in a new tab) ranks the signals: a redirect and a rel=canonical link are strong, a sitemap entry is weak. It also reads canonicals sent in the HTTP header, for web search results only, and asks you not to use robots.txt for canonicalization. The technical SEO audit checklist covers the checks this script leaves out.
3. Join the crawl with Search Console data
A crawl shows what your site says about itself. Search Console shows what Google does with it, and the useful findings sit where the two disagree. In the Performance report, open the Pages tab, click Export and choose CSV. Google truncates that export to 1,000 rows of representative examples, which covers a small site and can mislead you on a large one.
import csv, sys
def column(fields, *names):
return next(f for f in fields if f.strip().lower() in names)
def load_pages(path):
with open(path, newline="", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
url_col = reader.fieldnames[0] # "Top pages" in the Pages export
imp_col = column(reader.fieldnames, "impressions")
return {r[url_col]: int(r[imp_col].replace(",", "") or 0) for r in reader}
sitemap_csv, checks_csv, pages_csv = sys.argv[1:4]
in_sitemap = {r["url"] for r in csv.DictReader(open(sitemap_csv, newline="", encoding="utf-8"))}
checks = {r["url"]: r for r in csv.DictReader(open(checks_csv, newline="", encoding="utf-8"))}
impressions = load_pages(pages_csv)
out = csv.writer(sys.stdout)
out.writerow(["url", "problem", "impressions"])
for url in sorted(in_sitemap | set(impressions)):
c = checks.get(url, {})
if url not in in_sitemap:
problem = "gets impressions, missing from sitemap"
elif c and c["hops"] != "0":
problem = f"in sitemap but redirects ({c['hops']} hops)"
elif c and c["status"] != "200":
problem = f"in sitemap but returns {c['status']}"
elif c and c["canonical_state"] == "other":
problem = "in sitemap but canonical points elsewhere"
elif c and c["noindex"] == "True":
problem = "in sitemap but noindex"
elif url not in impressions:
problem = "in sitemap, no impressions in the export"
else:
continue
out.writerow([url, problem, impressions.get(url, 0)])
Run python3 cross_gsc.py urls.csv checks.csv Pages.csv > problems.csv. Each problem points to a different fix:
| Problem | Usual cause | Fix |
|---|---|---|
| Gets impressions, missing from sitemap | A new section never added, or old URLs still ranking | Add the canonical URLs, redirect the old ones |
| In sitemap but redirects | The sitemap still lists old addresses | List the final URL instead |
| In sitemap but returns a 4xx or 5xx | Deleted pages that the sitemap never dropped | Remove them, or restore the page if it should exist |
| Canonical points elsewhere | Duplicates listed next to their canonical | Keep only the canonical in the sitemap |
| Noindex | A template or plugin setting | Remove the noindex, or remove the URL from the sitemap |
| No impressions in the export | Not indexed, too new, or cut by the row limit | Check it in URL Inspection; on a big site, use the API below |
The join is exact. https://example.com/page and https://example.com/page/ count as two URLs, and if both show up in problems.csv, that inconsistency is a finding of its own. If impressions are a new metric for you, read how SEO impressions are counted before you judge a page by them.
When 1,000 rows is not enough: the Search Console API
Search Console's API returns up to 25,000 rows per request (the default is 1,000) and pages through the rest with startRow. Google's guide to getting all your performance data (opens in a new tab) adds three rules: the method exposes at most 50,000 rows per day per search type, you should query one day at a time, and data is typically available after 2 to 3 days. Grouping by page and query together can also drop some data, so totals from this query may not match the report's headline numbers.
def all_rows(service, site_url, day, dimensions=("page", "query")):
"""Every row Search Console exposes for one day, 25,000 at a time."""
start = 0
while True:
body = {
"startDate": day,
"endDate": day,
"dimensions": list(dimensions),
"type": "web",
"dataState": "final",
"rowLimit": 25000,
"startRow": start,
}
rows = service.searchanalytics().query(siteUrl=site_url, body=body).execute().get("rows", [])
yield from rows
if len(rows) < 25000:
return
start += len(rows)
This is the only piece in the article that needs an extra package. Build the service object with Google's google-api-python-client and the OAuth flow from Google's Search Console Python quickstart, using the read-only webmasters scope. Results come back sorted by clicks, so the first page of rows always holds your biggest pages and queries.
4. Group queries into topics with a few lines of Python
Export the Queries tab the same way you exported Pages, then let script 4 sort the queries into groups. It reduces each query to a set of meaningful words (dropping words like "how", "best" and "near", and trimming a plural s), walks the list from most to fewest impressions, and adds each query to the first group whose words overlap enough. The query with the most impressions names the group.
import csv, re, sys
STOP = {"a", "an", "and", "are", "best", "can", "do", "for", "how", "i", "in", "is",
"me", "my", "near", "of", "on", "or", "the", "to", "vs", "what", "with"}
def words(query):
tokens = re.findall(r"[a-z0-9]+", query.lower())
return frozenset(t[:-1] if len(t) > 3 and t.endswith("s") else t for t in tokens if t not in STOP)
def group(rows, threshold=0.6):
groups = [] # [head query, word set, member rows]
for query, impressions in sorted(rows, key=lambda r: -r[1]):
w = words(query)
for g in groups:
if w and len(w & g[1]) / len(w | g[1]) >= threshold:
g[2].append((query, impressions))
break
else:
groups.append([query, w, [(query, impressions)]])
return groups
if __name__ == "__main__":
with open(sys.argv[1], newline="", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
q_col = reader.fieldnames[0] # "Top queries" in the Queries export
i_col = next(c for c in reader.fieldnames if c.strip().lower() == "impressions")
rows = [(r[q_col], int(r[i_col].replace(",", "") or 0)) for r in reader]
out = csv.writer(sys.stdout)
out.writerow(["group", "query", "impressions"])
for head, _, members in group(rows):
for query, impressions in members:
out.writerow([head, query, impressions])
On a made-up Queries export for a running shoe store, the output looks like this:
group,query,impressions
trail running shoes,trail running shoes,2310
trail running shoes,best trail running shoes,1850
trail running shoes,trail running shoes for women,640
trail running shoes,trail shoes vs running shoes,350
trail running shoes,womens trail running shoe,280
running shoe store near me,running shoe store near me,900
how to clean running shoes,how to clean running shoes,520
how to clean running shoes,clean running shoes in washing machine,300
waterproof trail shoes,waterproof trail shoes,410
The threshold in group() sets how strict the match is. Raise it and groups get tighter, lower it and "how to clean running shoes" starts landing in the trail shoe group. Word overlap has hard limits, though. It does not know that "sneakers" and "shoes" mean the same thing, and it put a comparison query ("trail shoes vs running shoes") with a shopping one because the words match. Use each group as a candidate page: when two of your URLs pull impressions for the same group, check them for keyword cannibalization before you write a third.
Python for AI search: crawler access and intent labels
Two newer jobs fit the same toolkit. One is technical: making sure the crawlers behind ChatGPT, Claude and Perplexity can read the pages you want them to read. The other is analytical: labeling thousands of queries by intent, which word overlap cannot do.
5. Read robots.txt the way GPTBot or ClaudeBot does
OpenAI, Anthropic and Perplexity each run more than one bot, and each bot answers to its own name in robots.txt. Sorting them by job makes the list easier to remember:
| Job | OpenAI | Anthropic | Perplexity |
|---|---|---|---|
| Collect training data | GPTBot | ClaudeBot | None in its docs |
| Feed AI search answers | OAI-SearchBot | Claude-SearchBot | PerplexityBot |
| Fetch a page a user asked for | ChatGPT-User | Claude-User | Perplexity-User |
The training and search crawlers follow robots.txt. The user fetchers are where it gets loose: OpenAI says robots.txt rules may not apply to ChatGPT-User, Perplexity says Perplexity-User generally ignores them, and Anthropic's help article on its bots (opens in a new tab) says all of its bots, Claude-User included, honor robots.txt.
Blocking GPTBot or ClaudeBot tells those companies not to use your pages for training. Blocking a search crawler is what can keep you out of AI search answers, and OpenAI says a change for OAI-SearchBot takes about 24 hours to apply. The AI crawler checker mentioned at the start explains each bot in more detail.
import sys, urllib.error, urllib.request
from urllib.robotparser import RobotFileParser
UA = "my-seo-scripts/1.0 (contact: you@example.com)"
BOTS = ["Googlebot", "GPTBot", "OAI-SearchBot", "ChatGPT-User", "ClaudeBot",
"Claude-SearchBot", "Claude-User", "PerplexityBot", "Perplexity-User"]
def parser_follows_rfc9309():
rp = RobotFileParser()
rp.parse(["User-agent: *", "Disallow: /", "Allow: /*.html$"])
return rp.can_fetch("AnyBot", "https://example.com/page.html")
def load(site):
rp = RobotFileParser()
req = urllib.request.Request(site.rstrip("/") + "/robots.txt", headers={"User-Agent": UA})
try:
with urllib.request.urlopen(req, timeout=15) as resp:
rp.parse(resp.read(500 * 1024).decode("utf-8", "replace").splitlines())
except urllib.error.HTTPError as err:
unreachable = err.code == 429 or err.code >= 500
rp.parse(["User-agent: *", "Disallow: /"] if unreachable else []) # 4xx: no rules
return rp
if __name__ == "__main__":
if not parser_follows_rfc9309():
print("Warning: this Python ignores * and $ and longest-match rules in robots.txt\n")
site, paths = sys.argv[1], sys.argv[2:] or ["/"]
rp = load(site)
for bot in BOTS:
verdicts = ["allowed" if rp.can_fetch(bot, site.rstrip("/") + p) else "BLOCKED" for p in paths]
print(f"{bot:18}", " ".join(f"{p} {v}" for p, v in zip(paths, verdicts)))
Status handling follows RFC 9309 (opens in a new tab), the robots.txt standard. A 4xx response means a crawler may access anything, while a server error means it must assume everything is disallowed. The script reads 500 KiB, the minimum parsing limit the standard sets. Run it as python3 robots_ai.py https://example.com / /blog/. Against nytimes.com on November 21, 2026, it printed this:
Googlebot / allowed
GPTBot / BLOCKED
OAI-SearchBot / BLOCKED
ChatGPT-User / BLOCKED
ClaudeBot / BLOCKED
Claude-SearchBot / BLOCKED
Claude-User / BLOCKED
PerplexityBot / BLOCKED
Perplexity-User / BLOCKED
Three limits are worth knowing before you trust the output:
- Your Python version changes the answer. RFC 9309 says the most specific rule wins, an allow beats an equal disallow, and
*and$work as wildcards. Python's urllib.robotparser only gained that behavior in a 2026 fix (CPython issue gh-138907, also backported to 3.13 and 3.14). On 3.12 and older it takes the first matching rule and treats*and$as plain characters. Theparser_follows_rfc9309()test prints a warning when your copy is the old one. - Pass the token, not the full user-agent string. The parser keeps only the text before the first slash, so the full string of GPTBot reads as "Mozilla" and falls through to the
*group. - The file is not the firewall. This reads robots.txt and nothing else. A CDN or firewall rule that blocks a bot by user agent or IP address stays invisible to it, and a fetcher that ignores robots.txt is not stopped by it.
6. Label search intent with a model API
Word overlap groups "cheap trail shoes" with "trail shoes", but it cannot tell that one searcher wants a product page and another wants a guide. A language model can make that call for thousands of queries in a few minutes. Script 6 sends your queries in batches and forces the answer into a fixed list of labels with a strict JSON schema. The example uses OpenAI's Responses endpoint. Anthropic and Google offer the same pattern with a different request format.
import csv, json, os, sys, time, urllib.error, urllib.request
LABELS = ["informational", "commercial", "transactional", "navigational", "local"]
SCHEMA = {
"type": "object",
"properties": {"items": {"type": "array", "items": {
"type": "object",
"properties": {"query": {"type": "string"}, "intent": {"type": "string", "enum": LABELS}},
"required": ["query", "intent"], "additionalProperties": False}}},
"required": ["items"], "additionalProperties": False,
}
PROMPT = ("Classify each search query by the searcher's main intent. "
"Use 'local' only when the query asks for a place nearby. Queries:\n")
def classify(queries):
body = {"model": os.environ["LLM_MODEL"], "store": False,
"input": PROMPT + "\n".join(queries),
"text": {"format": {"type": "json_schema", "name": "intents", "strict": True, "schema": SCHEMA}}}
req = urllib.request.Request("https://api.openai.com/v1/responses", data=json.dumps(body).encode(),
headers={"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
"Content-Type": "application/json"})
for attempt in range(4):
try:
with urllib.request.urlopen(req, timeout=60) as resp:
data = json.load(resp)
break
except urllib.error.HTTPError as err:
if err.code != 429 and err.code < 500:
raise
time.sleep(2 ** attempt) # rate limit or server error: wait and retry
else:
raise RuntimeError("API kept failing")
text = next(c["text"] for o in data["output"] if o["type"] == "message" for c in o["content"])
got = {i["query"]: i["intent"] for i in json.loads(text)["items"]}
return {q: got.get(q, "unclassified") for q in queries} # never trust it to return every row
if __name__ == "__main__":
queries = [line.strip() for line in open(sys.argv[1], encoding="utf-8") if line.strip()]
out = csv.writer(sys.stdout)
out.writerow(["query", "intent"])
for i in range(0, len(queries), 50):
for query, intent in classify(queries[i:i + 50]).items():
out.writerow([query, intent])
Put one query per line in queries.txt, set the OPENAI_API_KEY and LLM_MODEL environment variables (the smallest model your account offers is usually enough for labels), and run python3 classify_queries.py queries.txt > intents.csv. For the same made-up queries plus two branded ones, it returned:
query,intent
trail running shoes,commercial
best trail running shoes,commercial
trail running shoes for women,commercial
waterproof trail shoes,commercial
womens trail running shoe,commercial
how to clean running shoes,informational
clean running shoes in washing machine,informational
running shoe store near me,local
trail shoes vs running shoes,informational
nike pegasus trail 5 price,commercial
rei login,navigational
Most labels are what an SEO would pick, and the comparison query that script 4 put in the shopping group came back as informational. "nike pegasus trail 5 price" is the row to argue about: the model called it commercial, while someone asking the price of one exact shoe may be ready to buy. That is the first limit: the model never sees the results page, so it guesses intent from the words while Google decides it from behavior. Spot-check a sample of rows against the live results before you plan pages around the labels.
The other limits are practical:
- The schema fixes the shape, not the truth. Strict mode guarantees a valid label from your list. It cannot guarantee the right one, and the script marks any query the model skipped as "unclassified" instead of trusting the reply to be complete.
- Write down the model and the date. If labels shift between two runs months apart, you will want to know whether the queries changed or the model did.
- Read your provider's data terms. Search Console already leaves out anonymized queries, but you are still sending your query list to a third party.
- Batch to keep the bill small. One request per query costs more and hits rate limits sooner. The script batches, and it backs off and retries on rate limit and server errors.
If you want an assistant to reason over a whole audit rather than label rows, the walkthrough on using Claude for SEO audits picks up where this section stops.
Slibur dataChatGPT, United States, 4 answers, November 21, 2026
What ChatGPT recommends when asked about Python for SEO
We asked ChatGPT four questions on November 21, 2026, from the United States: how to use Python for SEO and what to automate, which Python libraries are best for SEO automation, how to pull Google Search Console data with Python, and whether Python is worth learning for SEO in 2026.
The answers were consistent, and they share a few gaps:
- pandas was the one constant. It appeared in all four answers. Requests, Beautiful Soup and Google's API client appeared in three, and lxml, Scrapy, httpx and networkx in two.
- The standard library never came up. Three of the four answers included pip install commands, and none mentioned the modules that ship with Python for HTTP, XML, CSV or robots.txt.
- AI crawlers were missing. No answer named GPTBot, ClaudeBot or any other AI crawler. robots.txt came up once, as a feature of Scrapy.
- Two answers warned against scraping Google's results pages and pointed to APIs or licensed data providers instead.
- Sources leaned on Google. The three answers that cited sources linked to eight pages, five of them on developers.google.com. The first answer cited nothing. The Search Console answer got its limits right: 25,000 rows per request, data 2 to 3 days behind, and 50,000 rows per day per search type.
In practice, ChatGPT steers beginners to pandas and third-party packages first, and leaves out the newest robots.txt question entirely. The scripts above cover both gaps. If you publish SEO tools, courses or libraries, answers like these decide which names a beginner hears first, and a ChatGPT visibility tracker is how you find out whether yours is one of them. Slibur asks ChatGPT, Google AI Overviews, Claude, Perplexity and Grok the questions your customers ask, then shows which brands they name and which sites they cite.
Run the scripts on a schedule
A check you run once finds today's problems. A check on a schedule finds the problem the week it appears. On macOS or Linux, one cron line chains the first two scripts every Monday at 7:00:
0 7 * * 1 cd ~/seo && python3 sitemap_urls.py https://example.com/sitemap.xml > urls.csv && python3 check_urls.py urls.csv > checks.csv
Windows has Task Scheduler for the same job. A reasonable rhythm for the rest:
| Script | How often |
|---|---|
| Sitemap list and status check | Weekly, and after every release |
| Join with Search Console | Monthly with the export, weekly with the API |
| Query groups and intent labels | Monthly or quarterly |
| robots.txt check for AI crawlers | After any change to robots.txt, your CDN or your firewall |
Save each run in a folder named by date. Comparing two weeks of checks.csv shows what changed, and that difference is usually the whole report. Python will not lift a ranking by itself. It finds the redirect, the stray noindex or the blocked crawler sooner, and the fix is still yours. To see whether AI assistants name your brand once those pages are clean, start a 7-day free trial of Slibur, no card required.
Frequently asked questions
Do I need to be a programmer to use Python for SEO?
No. Most SEO scripts use a handful of ideas: variables, loops, functions, reading and writing CSV files, and making HTTP requests. Start by running a short script as it is, change one line, and run it again. Reading other people's scripts teaches you more than a general programming course.
Which Python libraries are most useful for SEO?
pandas for working with exports and crawl data, Requests or httpx for fetching pages, Beautiful Soup or lxml for parsing HTML, Scrapy for large crawls and google-api-python-client for Search Console. For one-off checks the standard library is enough: urllib, csv, xml.etree, html.parser and urllib.robotparser come with every Python install.
How do I get more than 1,000 rows from Search Console with Python?
Use the Search Console API instead of the export button. Each request returns up to 25,000 rows, and you page through the rest with startRow. Google exposes at most 50,000 rows per day per search type, so query one day at a time and expect the data to arrive 2 to 3 days late.
Is it safe to crawl a website with Python?
On your own site, yes, if you set a clear user agent, wait between requests and use timeouts. On other people's sites, follow their robots.txt and terms, and keep the request rate low. Scripts that hammer a server can get your IP address blocked.
Can Python check whether AI crawlers can read my site?
Yes. urllib.robotparser can test any path for tokens like GPTBot, OAI-SearchBot, ClaudeBot or PerplexityBot. Pass the short token, not the full user-agent string, and use a recent Python release, because older versions ignore the * and $ wildcards. It cannot see firewall or CDN rules that block bots.
Will Python improve my rankings?
Not by itself. Python finds problems faster and at a larger scale: redirect chains, wrong canonicals, pages missing from the sitemap, queries split across pages. The ranking change comes from fixing what the scripts find.

Raúl Díaz is the founder of Slibur, the tool that asks ChatGPT, Google AI Overviews, Claude, Perplexity and Grok the questions your customers ask and shows which brands they recommend. He writes about answer engine optimization from the data Slibur collects.