Python & Automation

Python for SEO: Seven Tasks Worth Automating

Python for SEO: Seven Tasks Worth Automating — featured image by ONYONKA J.M

Much of SEO is detective work, and much of the rest is repetition. Exporting the same reports every month. Checking hundreds of URLs for broken links. Comparing two spreadsheets of titles. Tasks like these are necessary and dull, and they consume hours that would be better spent thinking.

Python is the tool I reach for to get those hours back. It is a general-purpose programming language with a gentle learning curve and excellent libraries for handling data and talking to web services. You do not need to become a software engineer to benefit. A few dozen lines can replace an afternoon of copying and pasting, and will do the job identically every time.

This article explains why Python suits SEO work, what you need to start, and seven tasks that are worth automating, with short examples you can adapt.

Why Python for SEO?

  • It handles scale. A spreadsheet struggles with a few hundred thousand rows. Python processes millions without complaint.
  • It connects to data sources. Google Search Console, Google Analytics, PageSpeed Insights and most SEO tools offer APIs that Python can query directly.
  • It is repeatable. A script written once produces the same analysis next month with new data, with no manual steps to forget.
  • It is free and widely supported. The language and its libraries cost nothing, and almost any question you have has already been answered online.

Getting set up

The quickest way to begin is Google Colab, a free notebook environment that runs in the browser with nothing to install. For regular use, install Python on your computer and work in Jupyter notebooks or an editor such as VS Code.

A handful of libraries cover most SEO work:

  • pandas for loading, cleaning and analysing tabular data.
  • requests for fetching web pages and calling APIs.
  • beautifulsoup4 for extracting elements from HTML.
  • google-api-python-client for Google services.
  • plotly or matplotlib for charts.

Install them with one command:

pip install pandas requests beautifulsoup4 google-api-python-client plotly

1. Pulling complete Search Console data

The Search Console interface shows at most 1,000 rows per report. The API returns far more, which reveals the long tail of queries that the interface hides. Once you have created credentials in Google Cloud and authorised access to your property, a request looks like this:

from googleapiclient.discovery import build

service = build("searchconsole", "v1", credentials=creds)
body = {
    "startDate": "2026-08-01",
    "endDate": "2026-10-31",
    "dimensions": ["query", "page"],
    "rowLimit": 25000,
}
rows = service.searchanalytics().query(
    siteUrl="https://www.example.com/", body=body
).execute().get("rows", [])

Load the rows into pandas and you can answer questions the interface cannot: which queries rank in positions 8 to 20 with high impressions, which pages compete for the same query, and how non-branded clicks have changed quarter on quarter. Schedule the script to run monthly and store the results, and you also build a history that goes beyond the 16 months Google retains.

2. Checking status codes and redirects in bulk

Before a migration, after a launch, or as a routine health check, you need to know what every URL returns. This script reads a list of addresses and reports each one's status and final destination.

import requests
import pandas as pd

urls = pd.read_csv("urls.csv")["url"]
results = []
for url in urls:
    try:
        r = requests.get(url, timeout=10, allow_redirects=True)
        results.append({
            "url": url,
            "status": r.status_code,
            "final_url": r.url,
            "hops": len(r.history),
        })
    except requests.RequestException as e:
        results.append({"url": url, "status": "error", "final_url": str(e), "hops": 0})

pd.DataFrame(results).to_csv("status_report.csv", index=False)

Filter the output for error codes, or for more than one hop to find redirect chains. Testing a redirect map of several thousand URLs this way takes minutes; see how to redesign a website without losing rankings for where that fits in a migration.

3. Auditing titles, descriptions and headings

With requests and BeautifulSoup you can extract on-page elements from any list of pages.

from bs4 import BeautifulSoup

def audit(url):
    soup = BeautifulSoup(requests.get(url, timeout=10).text, "html.parser")
    desc = soup.find("meta", attrs={"name": "description"})
    return {
        "url": url,
        "title": soup.title.string.strip() if soup.title and soup.title.string else "",
        "description": desc["content"].strip() if desc and desc.get("content") else "",
        "h1_count": len(soup.find_all("h1")),
    }

df = pd.DataFrame([audit(u) for u in urls])
df["title_length"] = df["title"].str.len()
duplicates = df[df.duplicated("title", keep=False)]

In a few lines you have every missing description, every duplicated title and every page with no H1 or several. Dedicated crawlers do this too, but a script lets you add your own checks, such as whether each page mentions a required phrase or links to a particular URL.

4. Grouping keywords by intent and topic

Sorting a list of two thousand keywords by hand is slow. Simple rules handle much of it:

def intent(keyword):
    k = keyword.lower()
    if any(w in k for w in ["buy", "price", "cost", "near me", "hire"]):
        return "transactional"
    if any(w in k for w in ["best", "vs", "review", "compare", "top"]):
        return "commercial"
    if any(w in k for w in ["how", "what", "why", "guide", "tips"]):
        return "informational"
    return "unclassified"

keywords["intent"] = keywords["keyword"].apply(intent)

For topic grouping, a more robust approach clusters keywords that share ranking URLs in the search results: if two queries return mostly the same pages, they belong on the same page of yours. The classification is a first pass that a person then reviews, which is far quicker than starting from nothing. The underlying method is described in keyword research for Kenyan businesses.

5. Finding internal linking opportunities

Internal links are among the most controllable ranking levers, and opportunities are easy to miss on a large site. A script can scan the text of every page for mentions of a target phrase where no link to the target page exists yet.

target_url = "/seo-services"
phrase = "technical seo"
opportunities = []
for url in urls:
    soup = BeautifulSoup(requests.get(url, timeout=10).text, "html.parser")
    text = soup.get_text(" ").lower()
    links = [a.get("href", "") for a in soup.find_all("a")]
    if phrase in text and not any(target_url in l for l in links):
        opportunities.append(url)

The result is a list of pages where adding a relevant link would be natural. Combine it with crawl data to find pages with few incoming internal links, which are often under-performing for that reason alone.

6. Monitoring Core Web Vitals across many pages

Testing pages one at a time in PageSpeed Insights does not scale. The PageSpeed Insights API returns the same data programmatically, including real-user field metrics where available.

API = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"

def vitals(url, key):
    data = requests.get(API, params={"url": url, "strategy": "mobile", "key": key}).json()
    m = data.get("loadingExperience", {}).get("metrics", {})
    return {
        "url": url,
        "LCP_ms": m.get("LARGEST_CONTENTFUL_PAINT_MS", {}).get("percentile"),
        "INP_ms": m.get("INTERACTION_TO_NEXT_PAINT", {}).get("percentile"),
        "CLS": m.get("CUMULATIVE_LAYOUT_SHIFT_SCORE", {}).get("percentile"),
    }

Run it weekly across your key templates, save the output and you have a performance log that shows immediately when a new plugin or design change has slowed the site. The thresholds to compare against are in the Core Web Vitals guide.

7. Automating reports

Monthly reporting is the classic candidate for automation. A script can pull Search Console and Analytics data, calculate the month-on-month and year-on-year changes, generate charts and write the result to a spreadsheet, a PDF or a database that feeds a dashboard.

this_month = df[df["month"] == "2026-10"].groupby("page")["clicks"].sum()
last_month = df[df["month"] == "2026-09"].groupby("page")["clicks"].sum()
change = (this_month - last_month).sort_values()
biggest_losers = change.head(10)
biggest_winners = change.tail(10)

The time saved goes into interpreting the numbers, which is the part clients value. For how to present the output, see SEO reporting dashboards.

More ideas once you are comfortable

  • Log file analysis: parse server logs to see exactly which URLs Googlebot requests and how often.
  • Sitemap validation: fetch every URL in the sitemap and flag any that redirect, error or carry noindex.
  • Content inventory: word counts, publication dates and traffic per article to identify pages to refresh or merge.
  • Structured data generation: build JSON-LD for hundreds of products or locations from a spreadsheet.
  • Competitor monitoring: track changes to competitors' titles and page counts over time.

From script to scheduled job

A script you run by hand is useful. A script that runs itself is a system. Once a piece of analysis has proved its worth, the next step is to schedule it so the results appear without anyone remembering to press a button.

On a personal computer or a small server, the operating system's scheduler does the job: cron on Linux and macOS, Task Scheduler on Windows. A typical arrangement runs a data collection script in the early hours of the first day of each month, saves the output to a dated file or a database table, and sends a short email confirming that it finished. For teams that prefer not to maintain a server, cloud services such as scheduled functions or hosted notebooks can run the same code on a timer.

Three habits keep scheduled jobs trustworthy. First, log what happened on every run, including how many rows were collected, so a silent failure is noticed quickly. Second, handle errors deliberately: if an API is unavailable, the script should wait and retry, and alert someone if it still cannot complete. Third, store the raw data as well as the summary. When a question comes up six months later that nobody anticipated, the raw history is what allows you to answer it.

A worked example: a monthly content health check

To show how the pieces fit together, consider a mid-sized company blog with a few hundred articles. The marketing manager wants to know each month which articles are losing traffic, which are close to the first page, and which have technical problems.

A single scheduled script can do all of it. It pulls three months of Search Console data by page and query. It compares each article's clicks with the previous period and flags any that have fallen by more than a set percentage. It lists queries where an article ranks between positions 8 and 20 with meaningful impressions, since these are the easiest wins. It then requests each URL, records the status code, checks that a title, description and single H1 are present, and notes the word count. Finally it writes three tabs to a spreadsheet: articles to refresh, articles to push, and articles to fix.

The manager opens one file and has a prioritised work list for the month. Assembling the same information by hand would take most of a day, which in practice means it would not be done. This is the real benefit of automation: not just saving time on tasks you already perform, but making regular checks possible that would otherwise be skipped.

Common pitfalls for beginners

  • Starting too big. Automate one small, annoying task first. Success with a twenty-line script builds the confidence for larger projects.
  • Ignoring data quality. URLs with and without trailing slashes, mixed capitalisation and tracking parameters will be treated as different pages unless you clean them first.
  • Forgetting API limits. Most services cap the number of requests per day or per minute. Read the documentation and build in pauses.
  • Hard-coding dates and paths. Calculate date ranges relative to today so the script still works next month.
  • No comments or documentation. You will not remember how it works in a year. Write a few lines explaining what the script does and how to run it.

Working responsibly

Automation makes it easy to send many requests quickly, so some care is needed.

  • Be gentle with servers. Add a short pause between requests and avoid crawling other people's sites aggressively.
  • Respect robots.txt and terms of service. Do not scrape Google's results pages directly; use official APIs or licensed data providers.
  • Protect credentials. Keep API keys out of shared code and store them in environment variables.
  • Validate the output. Spot-check results by hand before acting on them. A bug can produce confidently wrong numbers.
  • Do not automate content creation at scale. Generating pages in bulk to target keywords falls under Google's scaled content abuse policy. Use Python to analyse and to assist, not to flood a site.

Do you need to learn it yourself?

If you work in SEO or analytics daily, learning basic Python is one of the best investments you can make; a few weeks of practice with pandas pays for itself quickly. If you run a business or a marketing team, you may only need the results. In that case, having the scripts built for you delivers the same saving in time.

I build custom automation, data pipelines and SEO tools as part of my Python development service, delivered with documentation so your team can run them. If there is a report or check that someone in your organisation repeats by hand every week, it is probably a candidate.

Onyonka J.M
Written by Onyonka J.M

SEO specialist, Python developer and SEO & CMS trainer based in Kenya, working with companies worldwide. About the author

Keep reading

Related guides

All articles

Onyonka J.M, SEO expert in Kenya Let’s work together

Ready to be found by the customers searching for you?

Tell me about your business and goals. I reply personally, usually within one working day.