Skip to content

Python for SEO: Scripts That Run Your Audits, Measured on a Live Site

Python Script for AI SEO Automation
Abu Talha

Abu Talha

AI SEO Expert

Table of Contents

SEO specialists use Python, a programming language, to execute optimization tasks as repeatable scripts instead of manual work. Python scripts automate technical SEO, on-page SEO, and reporting tasks at scale, loading crawl data into Pandas dataframes, sending requests with Python Requests, and parsing pages with BeautifulSoup.

Every claim on this page was run before it was written. The keyword-cleaning section reports what deduplication actually did to a real 8,830-row export: it removed 463 rows, inflated 6.1% of clusters, and distorted one word-frequency term by 55.9%. The clustering section reports that a single cosine threshold moved the cluster count from 2,340 to 6,775. The rate-limit section reports a 66.5% success rate, not a technique that works. Fifteen findings on this page carry numbers like these, and several of them contradict what the surrounding advice would lead you to expect.

Python runs technical SEO audits like status-code validation and page speed checks, then extracts page-level elements for on-page SEO. For semantic SEO, Python converts page text into meaning-level representations with NLP libraries and embeddings. Those embeddings feed AI SEO workflows, where machine learning builds predictive models and scores AI Overview readiness against retrieval and citation criteria. Scheduled scripts push CMS-level fixes back to WordPress SEO without manual input. These tasks run on established SEO tools such as Pandas, BeautifulSoup, Scikit-learn, and python-seo-analyzer.

What this page does not do is teach Python. It assumes you can read a loop, and it spends its space on what the output actually looked like when the script ran.

What is Python for SEO?

Python for SEO is a programming language that executes SEO tasks as repeatable scripts instead of manual work. Python is an SEO skill, not a developer-only language. Practitioners use programmable SEO (writing code that runs SEO work automatically) to replace repeated hand operations. Python operates across technical SEO, on-page SEO, semantic SEO, and WordPress SEO, and connects to machine learning for analysis-heavy tasks. Tasks become scripts, such as web scraping, keyword density calculation, and log file analysis.

Python scales SEO analysis past spreadsheet and manual limits. Python runs data operations across thousands of URLs in one pass. Python drives SEO tools and libraries, such as Pandas (data manipulation), BeautifulSoup (HTML parsing), and the python-seo-analyzer / analyzer script (automated site audit). Python supports AI SEO in two specific ways: it calls the OpenAI API to run content-quality judgments a rule-based check gets wrong, and it scores your own passages against retrieval criteria. It does not read Google’s index, and the limits of the second are measured later on this page.

Python wins on data work while JavaScript, R, PyPy, and Excel serve different SEO jobs, a split covered in the coding skills for SEO comparison. Running Python for SEO starts with a working environment.

How do you set up Python for SEO?

To set up Python for SEO, SEOs install a current Python 3 distribution and confirm it runs before writing any script. That takes three steps.

  1. Install a current Python 3 distribution from one of two routes: Anaconda (a bundled Python distribution with data libraries preinstalled) or Python.org (the official source release). Take whatever Python 3 release is current when you install; every library on this page supports the current and previous minor version, and nothing here depends on a specific one.
  2. Select the install route matching the SEO task, since Anaconda ships data libraries for technical SEO and on-page SEO work while Python.org gives a minimal base for SEO tools.
  3. Confirm the install runs by executing a short script, then add packages such as python-seo-analyzer (a ready-made Python SEO analyzer package).

Python runs SEO scripts after installation. Most SEO professionals reach a first useful script within two to four weeks of consistent practice, and Python for SEO asks for basic scripting literacy rather than developer-level skill; the prerequisite skills are listed separately.

Where do you run Python SEO scripts?

Python SEO scripts run in two execution contexts: a browser notebook that needs no local install, or a local editor on your own machine.

EnvironmentTypeInstall needed
Google ColabBrowser notebookNone
ReplitBrowser IDENone
Jupyter NotebookLocal notebookLocal Python
Visual Studio CodeCode editorLocal Python
Spyder IDEScientific editorLocal Python, usually via Anaconda
AnacondaDistribution bundling notebook and IDELocal install

This execution context is the setting in which every later script in this guide runs.

How does Python handle SEO data?

Python handles SEO data by loading it into Pandas dataframes (named tables in memory), then reading and writing it as CSV, JSON or XML. Python reads structured, tabular SEO data loaded into dataframes before any audit runs. Pandas performs this load across three standard formats: CSV (comma-separated values) for keyword exports, JSON (JavaScript Object Notation) for API responses, and XML (extensible markup language) for sitemap.xml files. Each format moves into a Pandas dataframe as one named table. Python reads raw exports this way, then writes results back in the same three formats. Cleaning the loaded data comes next.

How do you clean messy keyword data?

To clean messy keyword data, deduplicate, normalize and filter the keyword dataset in Pandas. Pandas is the Python library for data manipulation (reshaping and filtering rows and columns). Cleaning a keyword dataset in Pandas takes 4 steps.

  1. Deduplicate rows: drop exact and case-insensitive duplicate keywords.
  2. Normalize the case and trim whitespace across every keyword cell.
  3. Strip malformed tokens: empty strings, stray punctuation and encoding errors.
  4. Filter rows outside valid ranges so only usable keywords remain.

Duplicate and malformed keywords break analysis: duplicates inflate word frequency counts and split one query across rows, so keyword clustering and later audits return wrong group sizes. A normalized table feeds the SEO audit that tools such as python-seo-analyzer run, covering technical SEO and on-page SEO checks that other SEO tools and machine learning models consume.

Keyword export before and after deduplication, 8,830 rows to 8,367, with 6.1% of clusters inflated

The order matters, and the count after each step is what tells you where the damage came from:

import pandas as pd

df = pd.concat([pd.read_csv(f) for f in sources], ignore_index=True)
print(len(df))                                    # 8,830

df["keyword"] = df["keyword"].str.strip().str.lower()
print(len(df))                                    # unchanged

df = df.drop_duplicates(subset="keyword")
print(len(df))                                    # 8,367

Printing the length after each step, rather than only at the end, is what separates “the merge created the duplicates” from “one of the tools exported them”.

An 8,830-row keyword export assembled from three separate tool pulls dropped to 8,367 rows on deduplication alone; whitespace normalization and lowercasing removed no rows at all, and collapsing five self-concatenated strings removed three more. Not one of the three source columns contained a duplicate of its own, so every one of the 463 repeats came from the merge rather than from any tool. The distortion that followed showed up in cluster size rather than cluster count. The count barely moved. The sizes did: 230 clusters, 6.1% of the set, were inflated by at least one duplicate row. Word frequency took the same shape of damage, 5.9% inflated across the whole export and 55.9% on its worst single term, which is the number that decides which topics a frequency pass says the site should cover.

The output is a normalized keyword table ready for keyword clustering and an SEO audit.

How do you import Screaming Frog crawls?

To import a Screaming Frog crawl, you load its CSV export into a Pandas dataframe, and for an API-sourced crawl you flatten the JSON first. The desktop export is already a table, so pd.read_csv() is the whole step. A crawl API returns the same page data without the desktop run, but it returns JSON, not a table, and pandas.json_normalize() is what turns it into one.

Python ingests both CSV exports and vendor APIs into one analysis pipeline, with sources such as Screaming Frog, Semrush, Ahrefs, Majestic SEO, Bing Webmaster Tools, OnCrawl and Apify. A loaded crawl export exposes status codes (200, 301, 404), meta tags (title, description), internal links and broken links for auditing.

import pandas as pd

# desktop export: already a table
crawl = pd.read_csv("internal_html.csv")

# API response: one page, nested five levels deep
flat = pd.DataFrame([item])          # 17 columns, five holding whole objects
flat = pd.json_normalize(item)       # 92 columns, five still holding lists

One page pulled through an on-page crawl endpoint on 12 November 2026 returned 111 scalar values across 17 top-level fields nested five levels deep. pd.DataFrame([item]) accepts it and produces 17 columns, five of which hold an entire object in a single cell. pd.json_normalize() opens those into 92 columns and still leaves five holding Python lists, because the heading tags, the duplicate meta tags and the resource warnings each have a different length on every page. The response is readable, not directly tabular, and the columns that resist flattening are exactly the ones an on-page audit needs.

How do you run technical SEO with Python?

To run technical SEO with Python, you load crawl data into Pandas dataframes and automate audit tasks such as rendering diagnosis, bulk page speed checks and status-code validation. Python for technical SEO maps audit work onto the difference between crawl-based and content-based signals, which the Python for technical SEO guide separates. Python does three technical SEO tasks a crawler GUI cannot: it joins crawl output to Search Console and analytics data in one table, it re-runs the same audit on a schedule with the same parameters, and it compares rendered against raw HTML across a URL set in one pass. Speed is not the argument. A desktop crawler is multi-threaded and a plain Requests loop is not. Repeatability and joinability are.

Rendering means the browser executing a page’s JavaScript to build the final HTML. Selenium (a browser automation library) renders pages, so Python compares rendered HTML against raw HTML. This exposes JavaScript crawl gaps that Screaming Frog flags and shows where crawl budget (how many pages a search engine crawls) drains.

Python queries the PageSpeed API and Lighthouse in bulk. PageSpeed Insights returns Core Web Vitals field data and lab diagnostics per URL, which Pandas holds as rows for comparison across a URL set. It does not return a projected gain from any fix, so the projection is yours to model from the diagnostics, not the API’s to supply. These produce site-level health findings that require enrichment from Google Search Console and Google Analytics.

How do you crawl URLs and check status codes?

To crawl URLs and check status codes, Python Requests (the HTTP library) sends an HTTP request to each URL and records the returned response. Python Requests tests thousands of URLs without a paid crawler by looping a URL list and reading each response, so no licensed tool is required.

Python Requests captures four site-health signals per URL:

SignalWhat it detects
Status codeWhether the URL returns 200, 301, 404 or 5xx
Redirect chainHow many hops sit between the request and the final URL
Broken linksInternal links pointing at a non-200 destination
Response timeWhich URLs are slow enough to drain crawl budget
import requests
import pandas as pd

rows = []
for url in urls:
    r = requests.get(url, timeout=20, allow_redirects=True)
    rows.append({
        "url": url,
        "status": r.status_code,
        "final_url": r.url,
        "hops": len(r.history),
        "seconds": r.elapsed.total_seconds(),
    })

pd.DataFrame(rows).to_csv("status_audit.csv", index=False)

Writing the four fields in the same row is the point. A status code without its redirect chain cannot tell you whether a 200 was reached directly or after three hops.

Python maps the internal link graph to expose orphaned and deep pages. Internal links feed this graph, orphaned pages (URLs with no inbound internal link) surface as gaps, and internal linking depth records the click distance from the homepage. This technical SEO signal supports wider SEO audits.

Which libraries parse XML sitemaps?

Python libraries that parse XML sitemaps are BeautifulSoup, Python Requests and Pandas. A sitemap.xml file is the XML file listing indexable URLs, split into files of under 50,000 URLs each. Python runs 3 libraries across this file.

LibraryRole in the parse
Python RequestsRetrieves the raw XML over HTTP
BeautifulSoupParses the XML into <loc> nodes, including the index branch
PandasStores the extracted URLs as rows for comparison against the crawl

Python compares the parsed sitemap URL set against the crawl results to find the indexable URL set.

A sitemap index needs the extra step, which is where a parser quietly returns the wrong set:

import requests
from bs4 import BeautifulSoup

def sitemap_urls(url, seen=None):
    seen = seen or set()
    xml = requests.get(url, timeout=30).text
    soup = BeautifulSoup(xml, "xml")
    if soup.find("sitemapindex"):
        for loc in soup.select("sitemap > loc"):
            seen |= sitemap_urls(loc.text.strip(), seen)
        return seen
    return seen | {loc.text.strip() for loc in soup.select("url > loc")}

The recursion is the whole point. Without the sitemapindex branch this returns three URLs on the site below, because the index file’s <loc> elements point at child sitemaps rather than at pages, and nothing raises.

Parsing one site’s sitemap index and its three child files returned 49 declared URLs from 26,358 bytes of XML in 1.35 seconds; a crawl of the same site reached 51 URLs that returned 200. Reading the index file alone would have returned 3. Comparing the two normalized sets left two URLs declared in the sitemap that nothing on the site links to, four crawled pages the sitemap never declares, and two internal links pointing at 404s. Normalizing for case mattered as much as normalizing the trailing slash: one apparent orphan turned out to be linked under a capitalized path that redirects to the same canonical.

These parsed URLs become the indexable URL set, checked against crawl results to produce the three gap counts above. The server log answers a different question: which URLs Googlebot actually requests, rather than which URLs exist.

How do you analyze log files?

To analyze log files, you parse server log entries with Python (a programming language) using Pandas to aggregate every Googlebot request by URL, status code and timestamp. Log file analysis is the examination of raw server log entries that record each bot visit. Googlebot requests indexable URLs, status codes and page load response times, which the server logs as rows of bot behavior.

Python log file analysis surfaces four signals:

SignalWhat the log row shows
Bot behaviorWhich user agent requested the URL, and when
Crawl activityHow often each URL is requested over the window
Crawl errorsWhich requests returned 4xx or 5xx to the bot
Security threat detectionRequest patterns that do not match any declared crawler

Pandas groups log rows by URL and status code. A python-seo-analyzer (an analyzer script built in Python) extends log analysis for technical SEO audits, and machine learning classifies bot patterns. Aggregated request counts per URL show which URLs Googlebot requests most and least often, which is the distribution a crawl-budget argument rests on. Turning that distribution into a budget figure needs the site’s own log volume and crawl rate, which no script can infer from the log alone.

How do you scrape and call SEO APIs with Python?

To scrape and call SEO APIs with Python, you authenticate to each API endpoint, send requests through Python Requests or BeautifulSoup, and join the returned ranking, analytics and SERP data to the on-site audit dataset. When no export exists, the data comes from live API calls and web scraping: Python Requests and BeautifulSoup extract the values, and web scraping (programmatic page extraction) covers sources with no API.

Three Python extraction routes supply the external context an on-site audit cannot: the Google Search Console API, Google indexing APIs, and backlink APIs.

  • Google Search Console API extraction and backup: Python authenticates to the Google Search Console API using OAuth 2.0 (an authorization protocol) and exports query-level performance data. Python returns impressions and click-through rates. Python writes the exported rows to MySQL (a relational database) for retention, which matters because the API caps a single response: one 500-row request against one property returned 100 rows and accounted for 121 of 216 clicks, leaving 44% of the total outside the pull.
  • Indexing and URL Inspection APIs: Python submits indexation requests to the Google Indexing API and reads URL inspection verdicts in bulk from the Google URL Inspection API. The values are indexed pages and indexation requests.
  • Backlink and anchor text analysis: Python aggregates backlink API data to flag toxic links (manipulative inbound links) and anchor skew. The values are anchor text distribution, referring domains, spam scores, and disavow (link rejection file).

These routes extend the SEO tools used in technical SEO and on-page SEO audits. The python-seo-analyzer (an open-source Python SEO analyzer) parses on-page SEO signals, and machine learning scores the aggregated data. Unmetered API calls and scraping requests return HTTP 429 responses.

How do you handle scraping rate limits?

To handle scraping rate limits, space each request with a fixed delay, rotate random user-agents, and add retry backoff so a Python scraper stays under the server cap. A script gets blocked halfway through because unthrottled requests at scale cross the server’s rate limit.

Three controls keep a scraper from being blocked:

ControlWhat it variesValue used in the runs below
Request delayThe fixed interval between calls1 second on the paid API, 0.5 seconds on the page fetcher
Random user-agentsThe browser identity string per callA single declared bot user agent on the page fetcher
Retry backoffThe wait before re-sending a blocked callGrowing pause after each failure

Python Requests and BeautifulSoup run the request-and-parse loop across web scraping, SERP scraping, and People Also Ask extraction. Scraping carries an acceptance of blocking risk even with throttling.

Two runs from the same machine in the same week put a number on that risk. A paid SERP API at one-second intervals carried more than a thousand calls across six scripts without a single failure. A page fetcher at half-second intervals, sending a declared bot user agent, reached 230 third-party URLs and got usable responses from 153, a 66.5% success rate, with 22 of the 77 failures coming from one domain. The delay was shorter on the second run, but the delay is not what separated them: one target sells access and the other does not. The run also logged no status codes, only success or nothing, so a 403, a 429 and a timeout are indistinguishable in its output. That is the part worth copying in reverse, because without the status code there is no way to tell whether to slow down or to stop.

The fix for that blind spot is two lines, and it is the version worth copying:

import time, requests

results = []
for url in urls:
    try:
        r = requests.get(url, timeout=20, headers={"User-Agent": UA})
        results.append((url, r.status_code, len(r.content)))
    except requests.RequestException as e:
        results.append((url, type(e).__name__, 0))
    time.sleep(0.5)

Recording r.status_code and the exception class separately is what the 66.5% run did not do. With them, a 403 (stop) and a 429 (slow down) and a timeout (retry) are three different decisions. Without them they are one word: failure.

An official API removes rate-limit guesswork, which points to connecting Python to the GA4 API.

How do you connect Python to the GA4 API?

To connect Python to the GA4 API, Python authenticates through OAuth 2.0 and pulls GA4 session and conversion data into a Pandas dataframe. The GA4 API is the Google Analytics 4 reporting interface that returns session and conversion metrics. Authentication against Google’s reporting endpoints takes one of two routes. A service account uses a JSON key and no consent screen, and the account’s own email address has to be granted access to the property before any request succeeds. An OAuth user flow uses a client credentials file, opens a browser for consent once, and stores a refresh token for later runs. Unattended scripts take the first route; the second exists for scripts run by a person against their own account.

Connecting Python to the GA4 API takes 4 steps.

  1. Create a Google Cloud service account and enable GA4 API access.
  2. Authenticate with OAuth 2.0 against the GA4 reporting endpoint.
  3. Request session and conversion metrics from Google Analytics, keeping the call throttled and retry-safe.
  4. Load the response into a Pandas dataframe.

The python-seo-analyzer reads these dataframe rows into SEO reports.

The same request shape against the Search Console API is where the row cap shows itself:

request = {
    "startDate": "2026-10-13",
    "endDate": "2026-11-11",
    "dimensions": ["query", "date"],
    "rowLimit": 500,
}
rows = service.searchanalytics().query(siteUrl=PROPERTY, body=request).execute().get("rows", [])
print(len(rows), sum(r["clicks"] for r in rows))   # 100   121

Nothing in the response announces that the cap was reached. The only signal is the row count sitting under rowLimit while a total you already know does not add up.

Pulling one property through the Search Console API on 12 November 2026 returned 30 dated rows for a 30-day window, 216 clicks across 8,815 impressions. The same property’s interface export carries 1,531 query rows and records nothing about the window except the label “Last 3 months,” which is why a script that needs a date has to go to the API. Asking the API for query and date together, a combination the export cannot produce at all, returned 100 rows against a 500-row request and accounted for 121 of those 216 clicks. The remaining 95 clicks, 44% of the total, sat in rows beyond the limit and in the queries Google anonymizes and never returns. The API gives more than the export and still does not give everything, and it does not announce the gap.

These authenticated pulls become the data layer for SEO reports.

How do you do on-page SEO with Python?

To do on-page SEO with Python, you extract and audit page-level elements at scale with BeautifulSoup and Pandas. What Python extracts is markup: the signals a quality judgment starts from, not the judgment. The section on LLM audits below shows what happens when a rule reads markup and calls it quality. External SERP and analytics data joined to the site dataset supplies the page-level context Python audits.

Metadata and on-page element extraction pulls page identity signals from HTML. BeautifulSoup (an HTML-parsing library) parses HTML to pull titles, descriptions and headings into a table. BeautifulSoup extracts six on-page elements:

ElementWhere BeautifulSoup finds it
Meta tags<meta name="description"> in the head
Headings<h1> through <h6> in document order
Canonical tags<link rel="canonical"> in the head
Alt textThe alt attribute on each <img>
Word countText nodes left after stripping nav, header, footer and form
Title tags<title> in the head

The resulting table enables keyword and duplication diagnostics. Pandas holds the extracted elements in a table for word count and duplication checks across every URL. A python-seo-analyzer is a ready-made script running this extraction, and machine learning extends on-page SEO toward semantic SEO. These checks sit alongside technical SEO and WordPress SEO audits in a wider SEO tools stack.

Running the extraction across the 49 URLs in one site’s sitemap returned no missing meta descriptions and no missing canonical tags, but 36 pages with no H1 at all and 39 titles longer than 60 characters against a median of 99. Two title strings and two descriptions each appeared on two pages. The H1 gap is not random: all 13 pages that have one come from the newer section templates, and every older post opens on an H2 instead, which is a template fault rather than 36 separate ones. Checking a sample page’s rendered DOM against its raw HTML returned the same count both ways, so the absence is in the markup and not a client-side rendering artifact.

The table exposes the pattern a page-by-page check does not. What it cannot tell you is whether two of those pages mean the same thing, which is where meaning-level work starts.

How do you use Python for semantic SEO?

To use Python for semantic SEO, you convert page text into meaning-level representations with natural language processing (NLP) libraries that extract entities, topics and word frequency. Semantic SEO is the practice of optimizing for meaning and entity relationships rather than keyword strings. Python turns the string-level cannibalization and similarity findings from the previous section into meaning-level representations a machine learning (ML) workflow can consume. The move from keyword matching to meaning happens when Python stops comparing keyword density and starts comparing entity overlap and topic vectors.

Python handles three meaning-level jobs for semantic SEO:

  • Extracts entities and topics that define page identity with NLP libraries, reading BERT (Bidirectional Encoder Representations from Transformers) signals and word frequency.
  • Scores content against query meaning using BERT.
  • Groups pages by shared meaning instead of matching keyword strings.

The entity-extraction method runs in the semantic SEO node.

Two keywords from the same 8,367-keyword set landed in different clusters on string similarity: one in a group of 138, the other in a group of 7, because they share exactly one word out of five. Checking the same pair against live search results on 12 November 2026 put them back together. They shared three of seven organic sources, four of the AI Overview’s sources, and five of eight related searches, and one of those related searches was a member of the first keyword’s own 138-strong cluster. Google’s generated answer opened by naming both phrases in one sentence as the same thing.

String overlap separated two queries that the search engine treats as one intent, which is the whole distance between comparing keywords and comparing meaning. Grouping by that string overlap is still where most clustering starts, so it is worth seeing what it produces.

Which method clusters keywords by intent?

Scikit-learn clusters keywords by intent by grouping queries that share overlapping SERP results into topic clusters. Keyword clustering (grouping queries that share search intent) assigns each query to a topic cluster, a set of queries targeting one meaning. Python with Scikit-learn groups thousands of keywords automatically, replacing manual sorting.

The pipeline runs three steps. The input is a clean keyword table plus SERP data, held by Pandas before clustering. Scikit-learn vectorizes then clusters the queries. The output is intent-labeled clusters, each mapped to one target URL. SERP overlap (shared ranking URLs between two queries) is the intent signal Scikit-learn groups on. Scikit-learn belongs to machine learning, the technique class behind this grouping, and a python-seo-analyzer feeds parsed on-page SEO signals into the same keyword table.

Keyword cluster count for 8,367 keywords at three cosine thresholds: 2,340 at 0.40, 5,455 at 0.60 and 6,775 at 0.70

The threshold belongs in the script as a named variable, not buried in a call, because it is the number that decides the result:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import scipy.sparse as sp
from scipy.sparse.csgraph import connected_components

THRESHOLD = 0.60                      # 0.40 -> 2,340 clusters; 0.70 -> 6,775

X = TfidfVectorizer(ngram_range=(1, 2)).fit_transform(keywords)
sim = cosine_similarity(X, dense_output=False)
adjacency = sp.csr_matrix(sim >= THRESHOLD)
n_clusters, labels = connected_components(adjacency, directed=False)
print(n_clusters)                     # 5,455

Single linkage is what connected_components gives you, and that is a deliberate choice rather than a default to ignore.

One run grouped 8,367 deduplicated keywords in 0.4 seconds using TF-IDF over word unigrams and bigrams with single-linkage connected components. At a cosine threshold of 0.60 it returned 5,455 clusters, but only 914 of those held more than one keyword, so 54.3% of the set joined nothing and the median cluster size was 1. The threshold is not a detail to leave out: at 0.40 the same keywords returned 2,340 clusters and at 0.70 they returned 6,775, nearly three times as many, from one number. The mid-sized groups were clean, with 138 weight-loss queries and 68 vitamin-D queries landing where they belonged, while the largest group chained four unrelated conditions together through shared function words. Single linkage produces exactly that shape, a giant component beside a field of singletons, and a different linkage redistributes both.

Clusters mapped to single URLs prevent two pages targeting one intent.

Can Python detect keyword cannibalization?

Python detects keyword cannibalization by comparing query-URL pairs to surface competing pages. Keyword cannibalization is two or more pages on one site competing for the same query, which splits ranking signals. Pairwise similarity scores between pages reveal which of your own pages compete, with high-scoring pairs flagged as cannibalization candidates.

Python reads a query-URL export from Google Search Console and groups rows where multiple URLs rank for one query, with Pandas handling the grouping. The same approach surfaces thin content and duplicate content, measuring duplication levels per page pair.

A query-URL grouping over 30 days on one ecommerce property returned 100 pairs across 73 distinct queries, of which 20 had more than one ranking URL and 8 carried 25 or more impressions. Thirteen of the twenty were not cannibalized at all: they were the same page under a locale prefix or a variant query string, and treating them as competitors would have doubled the count and broken the site’s international targeting if acted on. Seven were genuinely different pages, the largest being the brand term itself at 330 impressions across four URLs, with the homepage at position 1.3 and a collection page at 1.1 on the same query. Month-level aggregates cannot separate true cannibalization from a canonical that changed during the window, so even the seven are an upper bound.

Python surfaces cannibalization at the query-URL level.

How do you generate embeddings?

Python generates embeddings in four steps. An embedding (numeric vector) is a list of numbers that represents the meaning of a page or query, so pieces with similar meaning sit close together in vector space.

  1. Install the library and model with Python.
  2. Choose the model: BERT (Bidirectional Encoder Representations from Transformers) or the OpenAI API are the two options.
  3. Pass each page’s text and each query through the model to return a vector.
  4. Store the resulting vectors for similarity scoring.

Python converts each page into an embedding and scores semantic similarity between pages and queries. The BERT score (semantic similarity measure) ranks those pairs, and the stored vectors feed the comparison. This step sits beside on-page SEO and technical SEO work, where SEO tools and the python-seo-analyzer read surface signals while embeddings read meaning for AI SEO. The machine learning layer applies the same vectors across WordPress SEO and semantic SEO audits.

Cosine similarity of four page pairs under TF-IDF (0.06 to 0.57) against averaged GloVe vectors (0.92 to 0.99)

Scoring the same pairs under two models side by side is what exposes the problem:

import numpy as np, gensim.downloader as api
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

tfidf = TfidfVectorizer().fit_transform([a_text, b_text])
print(cosine_similarity(tfidf[0], tfidf[1])[0][0])        # 0.48

wv = api.load("glove-wiki-gigaword-100")
vec = lambda t: np.mean([wv[w] for w in t.split() if w in wv], axis=0)
print(cosine_similarity([vec(a_text)], [vec(b_text)])[0][0])   # 0.99

Vectorizing four page pairs from one topical map shows why a similarity score means nothing without its model. Scored with TF-IDF after stripping every header, footer, nav and form, two sibling pages returned a cosine similarity of 0.48, a parent and its child 0.57, two pages in separate clusters 0.29, and two unrelated pages 0.06, which puts the usable threshold on this site near 0.40. Averaged glove-wiki-gigaword-100 word vectors compressed those same four pairs into 0.99, 0.99, 0.97 and 0.92, a total spread of 0.076, so no threshold separates anything. Report the model with the number or the number is not actionable. These vectors next compare page and query meaning.

How does Python power AI SEO workflows?

Python powers AI SEO workflows by scoring your own pages against retrieval criteria, across four stages that run as one pipeline. Python reads the embeddings you generated upstream from your own content, then runs audit and scoring routines over them. It does not read Google’s retrieval index and it does not sit inside generative search; what it measures is your side of the exchange. Python drives four stages:

  • Extracting data with Python Requests and BeautifulSoup.
  • Processing data with Pandas.
  • Running machine learning analysis (automated pattern detection from data) with Scikit-learn.
  • Scheduling audits with Cron.

These four stages are measurable end to end, and the run below measures them. What is not measurable is the thing they are pointed at. A readiness score ranks your pages against retrieval and citation criteria; whether Google then cited you is a fact the AI Overview does not fully report, and the last subsection here puts a number on how much of it goes unreported. Everything in this section is honest about which side of that line it sits on. The python-seo-analyzer, a named open-source analyzer among the SEO tools, runs the on-page SEO and technical SEO checks underneath, extending the practitioner Python work of Hamlet Batista and JR Oakes.

One end-to-end run over 11,726 input rows, a Search Console query export, a Search Console page export and a keyword research workbook, completed in 0.45 seconds across extraction, processing, clustering and output, writing 884 report rows that covered 786 keyword clusters and 98 striking-distance queries. Three consecutive runs returned 0.48, 0.44 and 0.44 seconds with identical counts, and clustering accounted for 93 percent of the total, which means the only stage worth optimizing in a workflow this shape is the machine learning one.

That run is the shape a scheduled job should have: read-only, fast, and repeatable. Whether a page is ready to be cited is a separate question, and a harder one to check.

Can Python call LLM APIs for content audits?

Python calls LLM APIs for content audits by sending page content to the OpenAI API (a hosted large language model endpoint) and returning structured audit verdicts, so a separate AI tool is not required for large-scale content quality evaluation. Python sends content to the OpenAI API and returns verdicts such as thin content flags, duplicate content levels, and readability scores, alongside AI content detection (machine classification of generated text) and the BERT score (semantic similarity measure). Python Requests posts page text to the OpenAI API, and Pandas structures the returned verdicts into a scored table, the same pattern python-seo-analyzer follows for on-page SEO and technical SEO checks.

An automated audit of one page on this site returned a low-content-rate verdict for a page carrying 1,982 words, because that check measures plain text as a share of total page weight and 13,041 bytes of copy inside a 189,073-byte Elementor DOM works out to 6.9 percent, below the 10 percent cutoff. Clearing the flag would have meant adding roughly 890 words to reach 2,870, which serves no reader. A language model reading the same page does not make that mistake, because it reads the words instead of dividing the bytes, and this is the whole reason the LLM layer is worth its cost.

How does machine learning extend Python SEO analysis?

Machine learning extends Python SEO analysis by building predictive models (forecasting and classification) layered on SEO datasets. Rule-based scripts flag conditions that are already known; machine learning (ML) predicts patterns no fixed rule describes. Rules handle fixed thresholds such as missing meta tags, broken links and status codes: the baseline that SEO tools and python-seo-analyzer cover across on-page SEO and technical SEO. Machine learning handles traffic forecasting and keyword clustering. Python applies machine learning to SEO analysis in three ways:

MethodWhat it predictsRun here?
ForecastingFuture search traffic from a historical performance seriesNo
ClassificationWhich topic cluster a keyword belongs to, with Scikit-learnYes: 8,367 keywords, 0.4 seconds
Causal inferenceWhat traffic would have done without a change, using a structural time-series model such as CausalImpact against an untouched control set of URLsNo

Causal inference is the one item on this list not run here. It needs a control set of URLs that did not receive the change and that tracked the test set closely before it, and on a site this size no such set exists. Python projects future search traffic from historical series to estimate ROI, feeding AI SEO and semantic SEO decisions, but a projection is not a measured lift and this page does not present one.

Those projections can be scored against outcomes.

Can Python score AI Overview readiness?

Python scores AI Overview readiness by grading passages against retrieval and citation criteria that answer engines apply. This answers whether a page will be quoted in an AI Overview as a plain fact. Python runs Answer Engine Optimization (AEO, optimizing passages for answer-engine citation), computing an AI Visibility Score by vectorization (converting passage text into numeric vectors) and comparing against citation criteria with BeautifulSoup, Python Requests, the OpenAI API and the BERT score. This settles the AI SEO domain and pivots to running scripts on schedule.

Python can score a page for AI Overview readiness, but validating that score is the hard part. Across 91 AI Overview sentences from 18 queries, 25 carried no reference at all and only 16 could be traced to a cited source at an overlap of 0.60 or better, and every single one of the 18 queries contained at least one unattributed sentence. A readiness score can rank pages on retrieval and citation criteria; it cannot be checked against citations that the overview never made.

These scoring routines still run one command at a time, which raises how you automate SEO tasks with Python scripts.

How do you automate SEO tasks with Python scripts?

To automate SEO tasks with Python, you write scripts that run four recurring task categories without manual input. The categories below are the four that survived into a schedule on this site; the sections above show the measured output of each.

  • Crawling pages and status checks with Python Requests and BeautifulSoup for web scraping (automated page data extraction).
  • Pulling report data such as sessions and clicks from Google Search Console and Google Analytics.
  • Grouping keywords into topic clusters with Scikit-learn, where Python scripts using Scikit-learn apply machine learning (automated pattern-based processing) to keyword clustering (grouping related queries).
  • Running the same clustering and reporting pipeline on a schedule: the four-stage run that finished 11,726 rows in 0.45 seconds and returned identical counts three times.

A Python script replaces a manual weekly routine by running the same audit, data pull, or clustering step on command. Python compiles recurring data pulls into dashboards and alert notifications using tools such as Flask, Matplotlib and Slack, covered in the dedicated automating SEO reporting section. Reliable SEO scripts depend on error handling (try...except blocks), linting and readable structure. The failure mode that matters most is the quiet one, treated next.

Which errors does an SEO script hide?

An SEO script hides the errors that return a value instead of raising one. Three runs on this page failed quietly, and in each case the script reported success.

The page fetcher at half-second intervals reached 230 URLs and got usable responses from 153. Its log recorded success or nothing, so a 403, a 429 and a timeout were one outcome in its output. The script did not crash; it under-reported, and 77 URLs disappeared without a reason attached to any of them.

The WordPress writer posted a meta description to the core meta object and the request returned 200. The pages endpoint registers eight meta fields and none belongs to the SEO plugin, so the write succeeded and changed nothing. A 200 is not confirmation that a value landed.

The Search Console pull asked for 500 rows of query-and-date data and got 100, covering 121 of 216 clicks. Nothing in the response says a limit was hit. The remaining 44% of clicks sat beyond the row cap and inside Google’s anonymized queries, and the only way to notice is to total the rows against a metric you already know.

rows = fetch(request)                          # returns 100
rows_clicks = sum(r["clicks"] for r in rows)   # 121
assert rows_clicks == known_total, f"{known_total - rows_clicks} clicks unaccounted"

An assert against a number you already know catches what the response does not announce. try...except catches the crash; the assert catches the lie.

How do you schedule a script to run automatically?

To schedule a script to run automatically, you register it with a system scheduler such as Cron, Crontab or Windows Task Scheduler that triggers execution on a fixed recurring interval. A closed laptop stops the script, so a cloud host such as Heroku, or a server kept running, executes the schedule instead.

Three tools schedule a Python SEO script on a recurring interval.

  • Cron (a Unix time-based job scheduler) runs jobs from Crontab (the Cron configuration file).
  • Windows Task Scheduler (the Windows equivalent) runs jobs on Windows.
  • Heroku runs jobs in the cloud after Git pushes the script to deployment.

A scheduled SEO job sends a failure notification through Slack or Gmail so a silent crash is caught, then delivers results and alerts after the run.

Scheduling is not a property worth having for its own sake, it is a property that depends on what the script does. Read-only jobs belong on a schedule: a rank check or a Search Console pull takes seconds, costs nothing, and an unattended failure means one missing row. The four-stage read-only run described earlier finished 11,726 input rows in 0.45 seconds and returned the same counts on three consecutive runs, which is exactly the profile of a job that is safe to leave alone. A pipeline that spends on API calls or writes back to the CMS is a different animal, and that one runs behind a manual gate here, because an unattended failure costs money or publishes something wrong. The honest version of this section is that I schedule the jobs that only read, and I gate the jobs that spend or write.

How do you automate WordPress SEO?

To automate WordPress SEO, you run Python scripts that read site data through an API and push CMS-level fixes back to WordPress. The automated script runs on a schedule, then writes back via API. Python sends data to WordPress, so it does more than read: it updates pages, meta tags and structured data through the WordPress REST API.

Python automates four WordPress SEO tasks:

  • Updates meta tags with Python Requests and the WordPress REST API.
  • Pushes structured data through the WordPress REST API.
  • Generates pages from page templates (reusable page layouts) merged with a keyword dataset.
  • Fixes broken links and canonical tags found by BeautifulSoup.

For programmatic SEO, Python combines page templates with structured data and a keyword dataset to produce WordPress pages at scale, with Pandas structuring the dataset. Scikit-learn applies machine learning to group keywords for these pages. The analyzer python-seo-analyzer audits on-page SEO before write-back, detailed in Python for WordPress SEO. These CMS-level fixes push back through the API.

Before writing back to WordPress through the REST API, send an OPTIONS request and read the registered schema. On this site the pages endpoint registers eight meta fields and none of them belongs to the SEO plugin, so a script that posts a meta description to the core meta object writes nothing while the request still succeeds, and the plugin’s own documentation confirms the field must be registered with show_in_rest first. The page builder adds a second trap, because the visible body copy lives in the builder’s meta field rather than the core content field. A writer that reports success and changes nothing is worse than a write that fails.

When Python is the wrong tool

Python is the wrong tool whenever a finished tool already measures the thing correctly and you only need it once. Four cases from the runs on this page show where the line falls.

A one-off check on a handful of URLs. The sitemap comparison above took 1.35 seconds to parse and about an hour to write. Screaming Frog does the same comparison from a menu. The script earns its hour only because it now runs on a schedule against three properties; run once, it loses.

A check where a tool’s defaults are already right. python-seo-analyzer 2025.4.3 returned 162 warnings on three pages, and 157 were the same ignorable one. Writing a custom extraction to avoid that noise was worth it here because the same extraction pulls 111 fields the library never reads. If the only complaint is noise, filter the tool’s output instead.

Anything where you cannot see what the metric measures. A content-quality rule flagged a 1,982-word page as thin because it divided copy bytes by DOM bytes and got 6.9%. The script was not wrong; the metric was. More Python would not have fixed it. Reading the metric definition would have, in two minutes.

Anything that spends money or writes to the site, unattended. Scheduling is covered above, and the short version is that read-only jobs belong on a schedule and jobs that spend or write belong behind a manual gate. A scraper that fails silently costs one missing row. A WordPress writer that reports success and changes nothing costs a week before anyone notices.

What Python is right for is the fifth case, which none of the four above describe: a number you currently take on trust and cannot check any other way.

Which Python SEO tools should you use?

Python SEO tools worth using are the data, scraping and machine-learning libraries that already solve common SEO tasks. Twelve libraries cover almost every script on this page.

LibraryWhat it doesWhich run on this page used it
PandasData manipulationAll fifteen
NumPyNumeric arraysClustering, embeddings
BeautifulSoupHTML and XML parsingSitemap parse, on-page extraction
RequestsHTTP requestsStatus codes, rate-limit runs
ScrapyCrawling frameworkNot used here
SeleniumBrowser automationNot used here
MatplotlibChartsNot used here
SeabornStatistical chartsNot used here
Scikit-learnMachine learningClustering, TF-IDF similarity
FlaskWeb appsNot used here
DjangoWeb appsNot used here
CausalImpactCausal inferenceNot run (see above)

Each is already built and tested, so the SEO practitioner does not rewrite scraping, parsing or statistics code from scratch. One packaged option, python-seo-analyzer, runs these checks for you.

What does python-seo-analyzer check?

python-seo-analyzer is an open-source Python tool that checks a site’s on-page SEO without writing code. python-seo-analyzer gives a one-command audit before any scripting, running from the command line over a site or sitemap.xml. python-seo-analyzer inspects word count, page titles and meta description tags (meta tags), heading structure (headings), and missing or duplicate content. The analyzer reports these technical SEO signals as a baseline, which machine learning and semantic SEO scripts extend later.

Running python-seo-analyzer 2025.4.3 across three published pages on this site returned 162 warnings, and 157 of them were the same warning: an anchor tag missing a title attribute, which Google ignores. The five that mattered were two titles over 70 characters and the fact that none of the three pages carries an H1, which a separate crawler had flagged independently. The crawl also walked 25 URLs and reported zero errors, 22 of which were HTTP 404 responses parsed as ordinary pages, because the library never reads the response status at all: its entire HTTP layer is twenty lines wrapping a urllib3 pool manager with no status check in it. That places python-seo-analyzer as a first-pass baseline on pages you already know resolve, not as a replacement for a crawler, and it explains why a custom extraction of 111 on-page fields is still worth writing.

python-seo-analyzer is a concrete off-the-shelf audit baseline that runs before custom scripts, alongside ready-made resources such as Kristin Tynski’s 23 notebooks and the scripts Hamlet Batista and JR Oakes published.

How do you learn Python for SEO?

To learn Python for SEO, you follow a staged path from programming basics to API automation. Python automation requires four base concepts: variables, loops, functions and dataframes (tabular data structures in Pandas), then error handling with try...except blocks.

The order that works is syntax first, then reference, then debugging: Codecademy or W3Schools for syntax, Python.org for reference, and Stack Overflow for the errors you will hit in week one. Kristin Tynski’s Colab collection belongs after that, not inside it. It holds 23 notebooks rather than a course, fewer than half of them are search-focused, and the last commit was August 2023, so several of the models they call have since been replaced. Read it once you can already read Python, and treat it as a catalog of what is possible rather than a syllabus.

Koray Tuğberk Gübür’s Holistic SEO walkthrough on checking sitemap status codes with Python was where my first working script came from. It pulled every URL out of the sitemap, requested each one, and wrote the status code and title to a CSV. The code in the article did not run as printed, and fixing it taught me more than copying it would have.

Python is not the tool for small one-off checks that an SEO platform or Screaming Frog already handles. It earns its place on repeated or large-scale work, where the same four stages run every time: extract, process, score, output.

Where it earns that place is visible in the fifteen runs listed below. None of them replaced a tool outright. Each one answered a question a tool reported wrongly or did not report at all: a crawler that called 404s ordinary pages, a rate-limit log that recorded no status codes, a similarity score that meant nothing without its model, a content-quality rule that flagged a 1,982-word page as thin. Python’s value on this site was not speed. It was being able to see what the tool was actually measuring.

Two things follow from here. If you cannot yet read a loop and a dataframe, start at coding skills for SEO and come back. If you can, the next thing worth scripting is whichever of the fifteen runs below matches a number you currently take on trust. The fastest one to reproduce is the sitemap-versus-crawl comparison, which needs Requests, BeautifulSoup and no credentials at all.

What was measured on this page

Every finding below ran on a live site before the section around it was written. The date column is the run date, not the publication date.

#SectionWhat ranWhat came out
1Clean messy keyword dataDeduplication over a merged 8,830-row export463 rows removed, all from the merge; 230 clusters (6.1%) inflated; one term inflated 55.9%
2Import Screaming Frog crawlsOne page through an on-page crawl endpoint, 12 Nov 2026111 scalar values, 17 top-level fields, 5 levels deep; json_normalize reached 92 columns, 5 still held lists
3Parse XML sitemapsOne sitemap index plus three child files49 declared URLs from 26,358 bytes in 1.35s; index alone returns 3; 2 orphans, 4 undeclared pages, 2 internal links to 404s
4Handle scraping rate limitsTwo runs, same machine, same weekPaid API at 1s: 1,000+ calls, zero failures. Page fetcher at 0.5s: 153 of 230 usable, 66.5%, 22 of 77 failures from one domain
5Connect Python to the GA4 APIOne property through the Search Console API, 12 Nov 202630 dated rows, 216 clicks / 8,815 impressions; query+date returned 100 of 500 requested, covering 121 of 216 clicks, 44% outside the pull
6On-page SEO extraction49 URLs from one sitemap0 missing meta descriptions, 0 missing canonicals, 36 pages with no H1, 39 titles over 60 chars against a median of 99
7Cluster keywords by intent8,367 keywords, TF-IDF unigrams+bigrams, single linkage0.4s; at 0.60 → 5,455 clusters, 54.3% singletons; at 0.40 → 2,340; at 0.70 → 6,775
8Detect keyword cannibalization30-day query-URL grouping, one ecommerce property100 pairs / 73 queries; 20 multi-URL, 8 with 25+ impressions; 13 of 20 were locale or query-string variants, not cannibalization
9Python for semantic SEOOne keyword pair checked against live results, 12 Nov 2026Different clusters on string similarity; shared 3 of 7 organic sources, 4 AI Overview sources, 5 of 8 related searches
10Generate embeddingsFour page pairs, two modelsTF-IDF spread 0.06–0.57 (usable threshold ≈0.40); averaged glove-wiki-gigaword-100 spread 0.92–0.99, total range 0.076
11AI SEO workflows11,726 input rows, four stages, three consecutive runs0.45s / 0.48s / 0.44s, identical counts; 884 report rows, 786 clusters, 98 striking-distance queries; clustering = 93% of runtime
12LLM APIs for content auditsOne 1,982-word page on this siteLow-content-rate flag: 13,041 bytes of copy in a 189,073-byte DOM = 6.9%, below a 10% cutoff. Clearing it needed ~890 added words
13Score AI Overview readiness91 AI Overview sentences across 18 queries25 carried no reference; 16 traceable to a cited source at ≥0.60 overlap; all 18 queries had at least one unattributed sentence
14Automate WordPress SEOOPTIONS request against the pages endpoint on this site8 registered meta fields, none belonging to the SEO plugin; body copy lives in the page builder’s meta field, not core content
15python-seo-analyzerVersion 2025.4.3 across three published pages162 warnings, 157 of them one ignorable warning; 25 URLs walked, zero errors reported, 22 of them HTTP 404

Not measured here. Three things on this page are described but were not run: CausalImpact split testing, Core Web Vitals projection from PageSpeed diagnostics, and crawl-budget allocation from server logs. The first needs a controlled test, the second needs a before-and-after deployment, and the third needs log access this site does not have. They are named because they belong in the task list, not because the numbers exist.

How these runs were made

Three properties appear in the table above, and the table names which is which: this site (talhabu.com, WordPress with a page builder, 49 URLs in its sitemap at the time of the runs), one ecommerce property (a client site, 30-day Search Console window), and one content property (the 8,830-row keyword export and the 8,367-keyword clustering set). Where a row says “one page” or “one property” without qualification, it is this site.

Everything ran on a single machine, Python 3 with pandas, scikit-learn, BeautifulSoup4, Requests and gensim at the versions current in November 2026. Two runs used paid APIs: a SERP API for the rate-limit comparison and an on-page crawl endpoint for the 111-field extraction. The table says so, because an API that never fails is not evidence that throttling works.

Where a number is a count, the script wrote it to a CSV and the count came from the file. Where a number is a timing, it is the mean of the runs stated in that row. No figure on this page was estimated, rounded up, or carried over from a previous run on different data. Three of them disagree with the advice in the section they sit in, and they are reported as they came out.

Abu Talha

Abu Talha

AI SEO Expert in Bangladesh. A 12+ years of experience helping businesses improve their online visibility, organic traffic, and digital growth. Expertise on Technical SEO, On-Page SEO, Semantic SEO, Topical Authority, AI SEO, SEO Content Strategy, WordPress SEO, Shopify SEO, WooCommerce SEO, and website optimization.

Related Articles

Join Our Mailing List

Sign up with 25000+ subscribers and get updates regularly. We share proven techniques and trending tips to grow website traffic.

Your subscription could not be saved. Please try again.
Your subscription has been successful.