Most guides to Python for SEO sell it as machine learning. The scripts that actually save time are boring: read a Search Console export with pandas, pull more rows than the interface allows, list every URL in a sitemap, and check titles across a few hundred pages. This guide gives you five short, working scripts for exactly those jobs, a simple test for deciding when a task deserves a script at all, and the mistakes that make SEO scripts quietly return wrong numbers.
What Python for SEO Actually Means
Python does nothing for rankings on its own. It gives you leverage over data: joining, filtering and repeating analysis that is slow or fragile in a spreadsheet. Three libraries cover most of the work. pandas handles tables (CSV exports, API results). requests fetches pages and files. BeautifulSoup parses HTML. Add Google’s API client for Search Console and you are set.
You do not need to be a developer. If you can write a nested spreadsheet formula, you can adapt these scripts. What matters more is knowing what question you are asking, the same skill behind a good Search Console performance analysis in the first place.
When a Script Beats a Spreadsheet: The Three-Question Test
Ask three questions before you write anything.
- Will you repeat it? Weekly or monthly tasks pay back the setup time. A one-off audit rarely does.
- Does it break the spreadsheet? Past tens of thousands of rows, joins across files, or regular expressions over every URL, spreadsheets get slow and error-prone.
- Does it need data the interface will not give you? The Search Console export caps at 1,000 rows. The API does not have that cap.
Two “yes” answers: write the script. One: a spreadsheet or free tool is faster. Zero: you are building a hobby.
| Task | Spreadsheet | Python |
|---|---|---|
| Sort one GSC export by impressions | Faster | Overkill |
| Same striking-distance report every month | Manual, easy to get wrong | Run once, reuse |
| Query and page data beyond 1,000 rows | Not possible from the UI export | Search Console API |
| Every URL across a sitemap index | Painful | A short function |
| Title checks on a few hundred URLs | Needs a crawler anyway | Possible, or use a crawler |
Set Up Once: Environment, Libraries and Secrets
Use a virtual environment so each project keeps its own library versions, then install the packages these scripts use:
python -m venv .venv
source .venv/bin/activate
pip install pandas requests beautifulsoup4 google-api-python-client google-auth defusedxml
Google Colab works if you would rather not install anything. Either way, never paste an API key or a service-account file into a script or a shared notebook. Store the path to the key file in an environment variable and read it with os.environ.
Script 1: Find Striking-Distance Queries in a GSC Export
Export the Queries table from the Search Console Performance report as CSV. This pandas SEO script finds queries with real demand where you rank just off the top of page one, usually the cheapest wins on a site. It renames the first column rather than relying on its exact header, which can differ by interface language.
import pandas as pd
df = pd.read_csv("Queries.csv")
df = df.rename(columns={df.columns[0]: "query"})
df.columns = [c.strip().lower() for c in df.columns]
df["ctr"] = df["ctr"].astype(str).str.rstrip("%").astype(float)
striking = df[df["position"].between(8, 20) & (df["impressions"] >= 100)]
print(striking.sort_values("impressions", ascending=False).head(25))
Scale the impression floor to your site: 20 for a small local site, 1,000 for a big publisher. Then improve the page that should rank for each query rather than spinning up a new one.
Script 2: Flag Pages That Underperform Their Own CTR Baseline
Generic CTR-by-position curves average other people’s sites and SERP layouts. Your own site is a better benchmark. This script builds a median CTR for each rounded position from your data, then flags rows that get far fewer clicks than your typical result at the same position. Run it on the Pages export (rename the first column to page instead).
df = df[df["impressions"] >= 50].copy()
df["bucket"] = df["position"].round().clip(upper=20)
baseline = df.groupby("bucket")["ctr"].median()
df["expected_ctr"] = df["bucket"].map(baseline)
under = df[(df["ctr"] < df["expected_ctr"] * 0.5) & (df["impressions"] >= 200)]
print(under.sort_values("impressions", ascending=False))
A flagged row is a question, not a verdict: low CTR can mean a weak title, a crowded SERP or a mismatched page. Check the title in a SERP snippet preview before rewriting anything, and change one batch at a time so you can measure the effect, the same discipline behind proper SEO experiments.
Script 3: Pull Past the 1,000-Row Limit with the Search Console API
Google’s own performance data deep dive confirms that the Search Console interface exports at most 1,000 rows. The Search Analytics API goes further: each request returns up to 25,000 rows, and you page through results with startRow, according to the API reference. Here is the core of a Search Console API Python fetch, using a service account whose email you have added as a user on the property:
import os
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
creds = service_account.Credentials.from_service_account_file(
os.environ["GSC_KEY_FILE"],
scopes=["https://www.googleapis.com/auth/webmasters.readonly"],
)
service = build("searchconsole", "v1", credentials=creds)
def fetch(site, start, end, dims=("query", "page")):
rows, start_row = [], 0
while True:
body = {"startDate": start, "endDate": end, "dimensions": list(dims),
"rowLimit": 25000, "startRow": start_row}
resp = service.searchanalytics().query(siteUrl=site, body=body).execute()
batch = resp.get("rows", [])
if not batch:
break
rows.extend(batch)
start_row += len(batch)
return pd.DataFrame([dict(zip(dims, r["keys"]), clicks=r["clicks"],
impressions=r["impressions"], ctr=r["ctr"],
position=r["position"]) for r in rows])
df = fetch("sc-domain:example.com", "2026-10-01", "2026-10-31")
Use sc-domain: for a Domain property or the full URL prefix for a URL-prefix property. Note that the API returns CTR as a fraction (0.05), while the CSV export shows a percentage, so do not mix the two without converting. Dates are in Pacific Time, and the API defaults to finalized data only.
Which Search Console Data Source to Use
The API is not unlimited either. Google’s guide to getting all your data says it exposes a maximum of 50,000 rows per day per search type, and that grouping by page or query may drop some data. The full picture:
| Source | Row limit | History | Best for |
|---|---|---|---|
| Performance report export | 1,000 rows | Up to 16 months | Quick looks, small sites |
| Search Analytics API | 25,000 per request; 50,000 per day per search type | Up to 16 months | Scripts, larger sites, monthly reports |
| Bulk data export to BigQuery | All performance data except anonymized queries | Starts from setup, no backfill | Large sites, long-term storage |
The BigQuery route needs a Google Cloud project with billing enabled, and Google’s bulk export help page says historical data before setup must come from the API. Because Search Console keeps only 16 months, a monthly script that saves results to your own storage is the cheap way to build long-term history.
Script 4: Extract Every URL From a Sitemap
Sitemaps are often split: Google’s sitemap documentation limits a single file to 50,000 URLs or 50MB uncompressed, so larger sites use a sitemap index that points to child sitemaps. This function follows the index, handles gzipped files and stops if a sitemap is listed twice.
import gzip
import requests
from defusedxml import ElementTree as ET
NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
HEADERS = {"User-Agent": "seo-audit-script ([email protected])"}
def sitemap_urls(url, seen=None):
seen = set() if seen is None else seen
if url in seen:
return []
seen.add(url)
resp = requests.get(url, headers=HEADERS, timeout=20)
resp.raise_for_status()
data = resp.content
if data[:2] == b"\x1f\x8b":
data = gzip.decompress(data)
root = ET.fromstring(data)
if root.tag.endswith("sitemapindex"):
urls = []
for loc in root.findall("sm:sitemap/sm:loc", NS):
urls += sitemap_urls(loc.text.strip(), seen)
return urls
return [loc.text.strip() for loc in root.findall("sm:url/sm:loc", NS)]
Why defusedxml rather than the standard library parser? Python’s own documentation warns that its XML modules are not secure against maliciously constructed data, and a competitor’s sitemap is data you do not control. Feed the list into Script 5, or compare it with your API page list to find sitemap URLs that never get impressions. For a quick one-off, the free Sitemap URL Extractor does the same job without code, and our walkthrough on extracting URLs from a sitemap covers the manual options.
Script 5: Check Title Tags Politely
Fetching pages turns analysis into crawling, so respect robots.txt and go slowly. Python’s standard library includes urllib.robotparser for the check. This script reuses requests, HEADERS and pandas from the earlier scripts, reads each host’s robots.txt once, skips disallowed URLs, waits between requests and records the title and its length.
import time
from urllib.parse import urlparse
from urllib.robotparser import RobotFileParser
from bs4 import BeautifulSoup
def check_titles(urls, agent="seo-audit-script", delay=1.0):
robots, results = {}, []
for u in urls:
host = "{0.scheme}://{0.netloc}".format(urlparse(u))
if host not in robots:
rp = RobotFileParser(host + "/robots.txt")
rp.read()
robots[host] = rp
if not robots[host].can_fetch(agent, u):
results.append({"url": u, "status": "blocked by robots.txt"})
continue
r = requests.get(u, headers=HEADERS, timeout=20)
soup = BeautifulSoup(r.text, "html.parser")
title = soup.title.get_text(strip=True) if soup.title else ""
results.append({"url": u, "status": r.status_code,
"title": title, "chars": len(title)})
time.sleep(delay)
out = pd.DataFrame(results)
out["duplicate"] = out["title"].duplicated(keep=False) & (out["title"] != "")
return out
Treat the character count as a rough flag, not a rule. Google’s title link documentation says there is no limit on how long a title element can be; the title link is truncated as needed to fit the device width. Empty titles and duplicates are the findings that matter most. For how to fix them, see our guide to writing SEO title tags.
Mistakes That Make SEO Scripts Lie
A script that runs cleanly can still be wrong. The usual failures:
- Reading raw HTML on a JavaScript site.
requestsfetches the source, not the rendered page. If titles or canonicals are injected by JavaScript, Script 5 reports what Google sees before rendering, which is why view source versus rendered HTML matters. - Trusting the robots parser on wildcard rules. In our test on Python 3.9,
urllib.robotparserallowed a URL that aDisallow: /*?sort=rule should block, because it does not treat*inside a path the way Google does. Check edge cases on your Python version, or with a robots.txt tester. - Expecting query and page totals to match the chart. Google says grouping by page or query may drop some data, and anonymized queries are withheld, so summed rows come in below property totals. Report totals from a query with no page or query dimension.
- Querying data that is not final. Google’s API guide says data is typically available after two to three days. Pull recent days later, or pass
dataStatedeliberately.
Where Python for SEO Stops and a Platform Takes Over
Python is excellent for the custom question no tool answers, and a poor way to rebuild a crawler, rank tracker or reporting stack: you inherit API changes, rendering, retries, storage and scheduling. Script 5 checks titles; a real audit needs JavaScript rendering, redirect chains, status codes and internal link data, which is why the SEO Rocket site audit runs on a real crawler (Screaming Frog-backed, with JS rendering) instead of a homemade loop.
The same split applies to Search Console. If your striking-distance and CTR checks are recurring, connect Search Console to SEO Rocket and ask for them in chat, with keyword research on real Ahrefs data alongside. It is the division we use ourselves, built on a playbook proven across 1,000,000+ ranking pages: scripts for one-off questions, a platform for anything you need every month. For more on picking which jobs to hand off, read what to automate in SEO.
FAQ
Do I need to learn Python to do SEO?
No. Many strong SEOs never write code. Python for SEO is a multiplier for people who already work with large exports or many sites, not a requirement for ranking pages.
What is the best Python library for SEO?
pandas, because most SEO work is table work. Add requests and BeautifulSoup for fetching pages and Google’s API client for Search Console, and you cover most everyday tasks.
Is it safe to scrape Google search results with Python?
No. Google’s spam policies list sending automated queries to Google, including scraping results for rank checking, as machine-generated traffic that violates its policies and Terms of Service. Use the Search Console API for your own data and a licensed data provider for rankings and keywords.
Can Python get more than 1,000 rows from Search Console?
Yes. The Search Analytics API returns up to 25,000 rows per request with paging, within a limit of 50,000 rows per day per search type. For complete data on very large sites, use the BigQuery bulk export.