Python SEO Automation: Practical Scripts From Search Console
How to set up Python SEO automation: working scripts for the Search Console API, bulk URL checks, PageSpeed reports and Turkish query analysis plus a checklist.
Python SEO automation means doing repetitive SEO work in code, the same way every time. Pulling Search Console data, checking the status of hundreds of URLs or producing the weekly report moves from manual work to a scheduled task with a few libraries and short scripts. In this post I explain the approach I use in my own work, with working code examples and their limits.
I started my career as a software developer, then moved into SEO and performance marketing. So when I do a task by hand for the third time, I start thinking about turning it into a script. Python is the most practical language for this, because it has mature libraries for working with data, HTTP requests and tables. The goal of this post is not to teach a Python course; it is to make five automations that genuinely help on the SEO side ready to set up.
Why is Python used for SEO?
Python is used in SEO to do repetitive, rule-based work quickly, accurately and at scale. An SEO specialist’s week is largely spent collecting the same data from different tools and combining it. Query data comes from Search Console, status codes from a crawler and speed data from PageSpeed Insights, each separately. Python merges these sources into one table and repeats the same analysis every week with the same rules.
The real problem with manual work is not time but inconsistency. One week the filter is set up differently, another week the date range shifts by a day. In code, the rule is written down and applied the same way every time. That makes week-over-week comparisons reliable.
Python is not the right tool for every job. The comparison below shows when a script is worth writing.
Do it by hand or with a ready tool
- The task is one-off or done once a month
- The data does not exceed a few hundred rows
- Everyone on the team will edit the result in a spreadsheet
- An existing tool already does the job completely
Automate it with Python
- The task repeats every week with the same rules
- There are thousands of rows or many sites
- Several data sources need to be combined
- The result will feed an alert or a report
I covered the broader frame of this approach in the marketing engineering post. Here the focus is only on practical scripts for SEO.
What do you need to get started?
To start with Python SEO automation, Python 3, a few libraries and access permission to Google APIs are enough. Installing the libraries in a virtual environment prevents version conflicts between projects.
python3 -m venv .venv
source .venv/bin/activate
pip install requests pandas google-api-python-client google-auth
These four libraries cover every example in this post:
- requests: Sends HTTP requests to web pages and APIs.
- pandas: Filters, groups and joins tabular data.
- google-api-python-client: Provides a client for Google APIs such as the Search Console API.
- google-auth: Handles authentication with a service account.
The cleanest way to access Search Console data from a scheduled script is a service account. A service account is an account in Google Cloud that belongs to an application and does not require a human login. You create a project in Google Cloud and enable the Search Console API. Then you create a service account, download its JSON key and add the service account’s email address as a user on the Search Console property.
How do you pull Search Console data with Python?
Short answer
How do you pull Search Console data with Python?
Search Console data is pulled with the Search Console API’s searchanalytics.query method. You authenticate with a service account and specify the date range and dimensions (query, page, country, device). A single request returns at most 25,000 rows; the remaining rows are fetched by paging with the startRow parameter and combined in a pandas table.
- Enable the Search Console API in a Google Cloud project
- Create a service account and download its JSON key
- Add the service account email as a user on the Search Console property
- Send a searchanalytics.query request with google-api-python-client
- Page through rows with startRow and load them into a pandas table
The performance table in the Search Console interface often falls short when you want to see every long-tail query. The Search Analytics method, by contrast, returns between 1 and 25,000 rows per request; the default is 1,000.[1] When you need more rows, you request the next page with the startRow parameter.[1] The function below handles that paging automatically.
import os
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
creds = service_account.Credentials.from_service_account_file(
os.environ["GSC_KEY_FILE"], scopes=SCOPES
)
gsc = build("searchconsole", "v1", credentials=creds)
def gsc_query(site, start, end, dimensions=("query", "page")):
rows, start_row = [], 0
while True:
body = {
"startDate": start,
"endDate": end,
"dimensions": list(dimensions),
"rowLimit": 25000,
"startRow": start_row,
}
resp = gsc.searchanalytics().query(siteUrl=site, body=body).execute()
batch = resp.get("rows", [])
rows.extend(batch)
if len(batch) < 25000:
break
start_row += 25000
df = pd.DataFrame(rows)
if df.empty:
return df
df[list(dimensions)] = pd.DataFrame(df.pop("keys").tolist(), index=df.index)
return df
df = gsc_query("sc-domain:example.com", "2026-10-01", "2026-10-28")
For domain properties, the siteUrl value is written with the sc-domain: prefix; for URL-prefix properties, in the form https://example.com/. Dates use the YYYY-MM-DD format and, according to Google’s documentation, are interpreted in Pacific Time (PT).[1] If you pull an end-of-day report on Turkish time, keep in mind that the last day’s data may not be complete yet.
What are the quota limits?
The Search Console API is free, but the number of requests is limited by quotas. According to Google’s usage limits page, Search Analytics queries are limited to 1,200 requests per minute per site and per user.[2] The same page notes that querying long date ranges and the same data over and over quickly exhausts the load quota.[2] In practice, the most efficient method is to pull data day by day, store it in a local file or database, and request only new days on each run.
How do you find query opportunities with pandas?
A query opportunity is a query that has high impressions but a low click-through rate (CTR), or sits at the top of page two. These queries are the candidates that respond fastest to title and meta description improvements or a content update. With pandas you can produce this list in a few lines.
opportunities = (
df[(df["impressions"] >= 200) & (df["position"].between(4, 15))]
.assign(ctr_pct=lambda d: (d["ctr"] * 100).round(2))
.sort_values("impressions", ascending=False)
[["query", "page", "impressions", "clicks", "ctr_pct", "position"]]
)
opportunities.to_csv("query-opportunities.csv", index=False)
The thresholds here (200 impressions, position 4 to 15) are a starting suggestion, not a rule. A small site needs a lower impression threshold, a large site a higher one. When more than one page shows up in the list for the same query, it deserves a separate look; that is often a sign of duplicate content or overlapping intent.
The İ/I trap in Turkish queries
The most common mistake in Turkish query analysis is lowercasing letters with Python’s standard lower() function. Python converts the capital “İ” into “i” plus a combining dot above (U+0307), and turns the capital “I” into “i” instead of the Turkish dotless “ı”. As a result, “İSTANBUL” and “istanbul” are not grouped as the same query, and “IŞIK” (light) wrongly becomes “işik”. This small detail directly affects the accuracy of query clustering on a Turkish site.
def tr_lower(text: str) -> str:
return text.replace("İ", "i").replace("I", "ı").lower()
df["query_norm"] = df["query"].map(tr_lower).str.strip()
summary = df.groupby("query_norm", as_index=False)[["clicks", "impressions"]].sum()
Some users search without Turkish characters (“sac ekimi” instead of “saç ekimi”, meaning hair transplant). To see these two spellings in one cluster, you can convert the characters to their ASCII equivalents in a separate column. Do not delete the original query, though, because the rankings and CTR of the two spellings can differ.
How do you automate bulk URL checks?
A bulk URL check reports the status code, redirects, robots.txt permission and index status of a URL list in a single run. It is the script you need most after a site migration, bulk redirects or a sitemap cleanup. The urllib.robotparser module in Python’s standard library reads a robots.txt file and tells you whether a given URL is open to a given crawler.[4]
import requests
from urllib.robotparser import RobotFileParser
rp = RobotFileParser("https://example.com/robots.txt")
rp.read()
def check(url):
r = requests.get(url, allow_redirects=True, timeout=15,
headers={"User-Agent": "seo-audit-script/1.0"})
return {
"url": url,
"status": r.status_code,
"final_url": r.url,
"redirect_count": len(r.history),
"robots_allowed": rp.can_fetch("Googlebot", url),
"noindex": "noindex" in r.headers.get("X-Robots-Tag", "").lower(),
}
result = pd.DataFrame([check(u) for u in url_list])
problems = result[(result["status"] != 200) | (result["redirect_count"] > 1) | ~result["robots_allowed"]]
You can fill the url_list variable from the sitemap, Search Console or a crawl export. Every URL in the sitemap should return 200 and contain no redirects; I explained why in the what is a sitemap post. Adding a short pause between requests is a simple way to avoid putting unnecessary load on your own server or CDN.
Index status with the URL Inspection API
The URL Inspection API is the programmatic version of the URL inspection tool in Search Console and returns a URL’s status in Google’s index.[3] This API has a limited quota: according to Google’s usage limits, you can make 2,000 queries per day and 600 per minute per site.[2] That is why you should check priority URLs that bring traffic or were recently published, not the whole site.
def index_status(site, url):
body = {"inspectionUrl": url, "siteUrl": site}
res = gsc.urlInspection().index().inspect(body=body).execute()
s = res["inspectionResult"]["indexStatusResult"]
return {"url": url, "coverage": s.get("coverageState"),
"last_crawl": s.get("lastCrawlTime"),
"google_canonical": s.get("googleCanonical")}
The googleCanonical field is especially valuable here. If the canonical URL Google chose differs from the one you declared, the page is often dealing with a duplicate issue or inconsistent internal links. You can find the interface equivalents in the how to use Google Search Console guide.
PageSpeed and Core Web Vitals report
PageSpeed Insights API is a Google API that returns a Lighthouse lab measurement for a URL, plus real-user data where available, as JSON.[5] According to Google’s documentation, the API can be called without a key, but a key is recommended for frequent, automated queries.[5] The function below collects the mobile performance score and LCP value for the sample URLs you pick for each template.
PSI = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
def speed(url):
p = {"url": url, "strategy": "mobile", "key": os.environ["PSI_KEY"]}
j = requests.get(PSI, params=p, timeout=120).json()
lab = j["lighthouseResult"]
field = j.get("loadingExperience", {}).get("metrics", {})
return {
"url": url,
"score": round(lab["categories"]["performance"]["score"] * 100),
"lab_lcp_ms": lab["audits"]["largest-contentful-paint"]["numericValue"],
"field_lcp_ms": field.get("LARGEST_CONTENTFUL_PAINT_MS", {}).get("percentile"),
}
Rather than measuring every URL one by one, it makes more sense to pick a few samples from each page template (home, category, product, blog). Pages that share a template usually share the same speed problems. I explained how to fix the problems you find in detail in the page speed optimization post.
How do I schedule the automation?
Writing the script is half the job; its value shows when it runs regularly without human intervention. The flow I use has four steps.
As a scheduler you can use cron on a server, a scheduled job in GitHub Actions or a scheduled task in Google Cloud. What matters is tying the result to a threshold instead of just writing it to a file. For example, getting a notification when “a sitemap URL that returned 200 yesterday returns 404 today” or “one of the priority pages dropped out of the index” is more useful than opening the report every day. If you want to combine reporting with AI-assisted flows, the human-in-the-loop approval from the AI marketing automation post applies here as well.
Search Console data on its own does not contain personal data, but that changes when you add CRM or form data to the same table. In an automation that processes personal data under KVKK (Turkey’s personal data protection law), data minimization, retention period and access rights must be defined from the start.
Is it safe to generate content with Python?
Using Python to collect, audit and report data is safe; generating large numbers of pages automatically needs care. Google’s spam policies define producing many pages that add no value for users, in order to manipulate rankings, as scaled content abuse. In that definition, what matters is not the production tool but the value the page adds for the user.
Programmatic SEO (generating many pages from a data table with a template) is therefore a separate decision. If every page rests on real and distinct data, for example each product’s own technical specifications, template-based generation can make sense. If the pages are copies with only a city or keyword name swapped, the risk outweighs the reward. My preference is to use Python not to write content, but to prepare the data that informs content decisions.
Conclusion
Python SEO automation takes over not the specialist’s decision, but the repetitive data work that comes before it. The order that pays off most at the start is this: first pull Search Console data regularly, then report query opportunities and URL statuses, and finally add speed and index checks. Let each script answer a single question and tie its result to a threshold.
If you need help on the code side or a reporting setup tailored to your own site, I described how I work on the software development page. If you would rather start with crawling, the how to use Screaming Frog guide is a good intermediate step before moving to Python.
Key terms
- Search Console API
- Search Console API is an interface that gives programmatic access to performance, sitemap and URL inspection data in Google Search Console. It lets you pull data by query and page without hitting the table and export limits of the interface, and connect that data to regular reports.
- Service account
- Service account is a Google Cloud account that belongs to an application rather than a person and accesses Google APIs without a human login. Once added as a user to a Search Console property, scheduled scripts can read that property's data automatically.
- pandas
- pandas is an open-source data analysis library for Python used to read, filter, group and join tabular data. In SEO automation it is used to combine Search Console, crawl and analytics data in a single table.
Frequently asked questions
Do you need to learn Python for SEO?
It is not mandatory, but it speeds up repetitive work. Exporting Search Console data, checking the status codes of hundreds of URLs or producing the weekly report in the same format become a few minutes of work with Python. Basic syntax plus the requests and pandas libraries are enough to start.
Which SEO tasks can be automated with Python?
The most common tasks are pulling Search Console performance data, bulk URL and index status checks, robots.txt and sitemap audits, PageSpeed Insights reports, internal link analysis and query clustering. What they have in common is that they follow clear rules and repeat often.
Is the Search Console API free?
There is no fee for using the Search Console API, but Google enforces quota limits. Search Analytics queries are limited to 1,200 requests per minute per site, and URL Inspection queries to 2,000 requests per day per site. These limits are published on Google's official usage limits page.
Python, Google Sheets or Screaming Frog?
Each fits a different job. Screaming Frog is faster for a one-off crawl, and Google Sheets for small tables shared within a team. For work that repeats the same way every week, combines several data sources or involves thousands of rows, Python is the more robust choice.
Does generating content automatically with Python hurt SEO?
Whether it hurts depends on the value of the content. Google's spam policies define producing many low-value pages to manipulate rankings as scaled content abuse. Using Python to collect and audit data is safe; generating pages requires human review.
Sources
The full topic: Software guide ↗ · Technical SEO guide ↗