Python for SEO: A Beginner’s Guide to Writing Scripts with ChatGPT or Claude

  • Updated
  • Reading time 15 min
Python for SEO beginner guide, Marketer Coffee
Table of contents 18
  1. What can Python actually do for an SEO?
  2. Do you need to know how to code before you start?
  3. What is the simplest setup for running SEO scripts?
  4. How should you prompt ChatGPT or Claude to write an SEO script?
  5. Example 1: how do you check status codes for a list of URLs?
  6. Example 2: how do you extract titles and meta descriptions in bulk?
  7. Example 3: how do you find “striking distance” keywords in a Search Console export?
  8. Example 4: how do you see which pages lost clicks between two periods?
  9. Which SEO tasks should you script next, and which should you leave to tools?
  10. How do you use AI assistants to understand code, not only write it?
  11. When does it make sense to bring in Marketer Coffee?
  12. Frequently asked questions about Python for SEO
    1. Is Python worth learning for SEO in 2026?
    2. Can ChatGPT or Claude write SEO scripts that work on the first try?
    3. Which Python libraries should an SEO beginner learn first?
    4. How do I get more than 1,000 rows from Search Console?
    5. Is it safe to run SEO scripts against any website?
  13. What should you remember about Python for SEO?

Python for SEO means using short scripts to do the repetitive parts of search work: checking hundreds of URLs, pulling titles and meta descriptions, and slicing Search Console exports faster than a spreadsheet allows. You do not need to become a developer to get value from it. In 2026 you can describe the task to ChatGPT or Claude in plain English, get a working script back, run it, and check the result.

The skill that matters is not memorizing syntax. It is knowing what to ask for, how to run the code safely, and how to tell whether the output is right. A beginner who can read a 20-line script and spot a wrong column name will get more done than someone who copies code blindly.

This guide gives you a setup that takes about ten minutes, a prompt pattern that produces usable scripts, and four tested examples you can run today: a status code checker, a title and meta description extractor, a “striking distance” keyword finder for Search Console data, and a period comparison that shows which pages lost clicks.

Every script below was run on sample data before publishing, so you can copy it as a starting point and adapt it with your AI assistant.

What can Python actually do for an SEO?

Python is most useful where you repeat the same check on many rows of data. If a task takes you more than an hour in a spreadsheet, or you do it every month, it is a candidate for a script.

Typical beginner-friendly jobs include:

  • Checking status codes and redirects for a list of URLs after a migration
  • Extracting titles, meta descriptions, H1s or canonical tags from many pages
  • Filtering and grouping Search Console exports by query, page or pattern
  • Comparing two time periods to find pages or queries that lost traffic
  • Merging data from different tools on a shared URL column
  • Pulling more Search Console rows than the interface lets you export

Python does not replace a crawler such as Screaming Frog or an all-in-one platform. It fills the gaps between them: the one-off question your tool does not answer, or the report you build the same way every month. Our list of SEO tools we use covers the commercial side of the stack.

Do you need to know how to code before you start?

No, but you need to be able to read code well enough to check it. AI assistants write plausible code quickly, and plausible is not the same as correct. A script can run without errors and still count the wrong column or skip half your URLs.

A realistic beginner goal is this: you can open a script, find where it reads the input file, see which columns it uses, and understand what it writes out. That level takes a few evenings, not months. Ask the assistant to add comments to every block, and ask it to explain any line you do not follow.

Three habits protect you from most mistakes:

  1. Test on a small sample first. Run the script on 10 URLs or 20 rows where you already know the answer.
  2. Spot-check the output. Open three results manually in the browser or the original export and compare.
  3. Never paste secrets. Do not give an AI chat your API keys, client passwords or personal data from exports.

What is the simplest setup for running SEO scripts?

You have two good options: a browser notebook with nothing to install, or Python on your own computer.

Two ways to run Python for SEO as a beginner
OptionBest forWhat to know
Google Colab (browser notebook)First experiments, sharing with colleaguesNo installation. Upload a CSV to the session, run cells one by one. Files disappear when the session ends unless you save them to Drive.
Python on your computerRegular reports, larger files, scheduled tasksInstall Python 3 from python.org, then run pip install requests beautifulsoup4 pandas in a terminal. Run scripts with python script_name.py.
Code editor (optional)Reading and editing scripts comfortablyVS Code or any editor with Python support highlights errors and makes indentation visible.

The examples in this guide use three libraries. requests fetches web pages. Beautiful Soup (package name beautifulsoup4) reads HTML and finds tags. pandas works with tables, which is what most SEO data is. All three are free, widely documented and well known to AI assistants, which means generated code that uses them tends to be reliable.

How should you prompt ChatGPT or Claude to write an SEO script?

Describe the input, the output and the edge cases, not just the goal. “Write a Python script to check my URLs” produces generic code. A specific prompt produces something you can run on the first try.

A prompt structure that works well:

  1. Context: “I am an SEO, not a developer. I run Python 3 locally.”
  2. Input: “I have a file urls.txt with one URL per line.” Or paste the header row and two sample rows of your CSV.
  3. Task: “For each URL, record the HTTP status code without following redirects, and the redirect target if there is one.”
  4. Output: “Save a CSV with columns url, status, redirect_to_or_error, and print the results.”
  5. Edge cases: “Do not stop if a URL times out or the domain does not resolve. Use a 10 second timeout.”
  6. Constraints: “Use only requests, Beautiful Soup and pandas. Add a comment above each block.”

When the script fails, paste the full error message back into the chat and say what you ran. Both ChatGPT and Claude are good at fixing their own code when they see the exact traceback. If the output looks wrong rather than crashing, describe what you expected and what you got, with one example row.

The four examples below were built this way, then trimmed and tested.

Example 1: how do you check status codes for a list of URLs?

This script reads URLs from a text file, requests each one without following redirects and saves the status codes to a CSV. It is the first thing to run after a migration, a redirect map update or a sitemap cleanup.

Create a file called urls.txt with one URL per line, save the script next to it as check_status.py and run it.

import csv
import requests

HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; MySEOCheck/1.0)"}

with open("urls.txt", encoding="utf-8") as f:
    urls = [line.strip() for line in f if line.strip()]

results = []
for url in urls:
    try:
        r = requests.get(url, headers=HEADERS, timeout=10, allow_redirects=False)
        results.append([url, r.status_code, r.headers.get("Location", "")])
    except requests.RequestException as e:
        results.append([url, "ERROR", type(e).__name__])

with open("status_report.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["url", "status", "redirect_to_or_error"])
    writer.writerows(results)

for row in results:
    print(*row, sep="\t")

What to look for in the output:

  • 200: the page loads. Good for URLs that should be live and indexable.
  • 301 or 308: permanent redirect. Check that the target in the third column is the right page and not the homepage by default.
  • 302 or 307: temporary redirect. Often a sign that a permanent redirect was set up incorrectly.
  • 404 or 410: the page is gone. Fine if intended, a problem if the URL is in your sitemap or internal links.
  • 5xx or ERROR: server or connection problem. Re-run later; if it persists, raise it with your developer.

The script sets allow_redirects=False on purpose. If you let requests follow redirects, a 301 chain would show up as a 200 and you would miss the redirect entirely. Ask your assistant for a version that follows the chain and lists every hop if you are auditing redirect chains.

Be polite with request volume. For a few hundred URLs on your own site this is fine. For thousands, ask the assistant to add a short pause between requests, and never point a script like this at a site you do not have permission to test.

Example 2: how do you extract titles and meta descriptions in bulk?

This script fetches each URL, reads the HTML with Beautiful Soup and records the title, the meta description and their lengths. It is a quick way to find missing, empty or duplicated snippets on a set of pages, for example every product in one category.

import csv
import requests
from bs4 import BeautifulSoup

HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; MySEOCheck/1.0)"}

def get_title_and_description(html):
    soup = BeautifulSoup(html, "html.parser")
    title = soup.title.get_text(strip=True) if soup.title else ""
    tag = soup.find("meta", attrs={"name": lambda v: v and v.lower() == "description"})
    description = tag.get("content", "").strip() if tag else ""
    return title, description

with open("urls.txt", encoding="utf-8") as f:
    urls = [line.strip() for line in f if line.strip()]

with open("meta_report.csv", "w", newline="", encoding="utf-8") as out:
    writer = csv.writer(out)
    writer.writerow(["url", "title", "title_length", "description", "description_length"])
    for url in urls:
        try:
            r = requests.get(url, headers=HEADERS, timeout=10)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        title, desc = get_title_and_description(r.text)
        writer.writerow([url, title, len(title), desc, len(desc)])
        print(url, "|", title or "MISSING TITLE", "|", desc or "MISSING DESCRIPTION")

Two details make this more robust than the first draft most assistants produce. First, it finds the meta description regardless of capitalization, because some CMS templates output name="Description". Second, it skips non-200 responses, so error pages do not pollute the report with titles like “Page not found”.

Open meta_report.csv in your spreadsheet and sort by title_length and description_length. Zero means missing. Then sort by title to find duplicates. Length is a rough guide only: Google rewrites snippets when it thinks a different text fits the query better, so treat this as a hygiene check, not a ranking fix. Our on-page SEO guide explains what to write once you know which pages need work.

One limitation: requests downloads the raw HTML, so titles that JavaScript adds after load will not appear. For JavaScript-heavy sites you may need a headless browser, a step beyond beginner level.

Example 3: how do you find “striking distance” keywords in a Search Console export?

This script reads the Queries file from a Search Console export and lists queries with a meaningful number of impressions where your average position is between 4 and 15. These are often the fastest wins: Google already considers the page relevant, but it sits just below or at the bottom of the first page.

In Search Console, open the Performance report, choose a date range, click Export and pick CSV. You get a ZIP file with several CSVs. This script uses Queries.csv.

import pandas as pd

df = pd.read_csv("Queries.csv")
df.columns = ["query", "clicks", "impressions", "ctr", "position"]
df["ctr"] = df["ctr"].str.rstrip("%").astype(float)

opportunities = df[
    df["position"].between(4, 15) & (df["impressions"] >= 500)
].sort_values("impressions", ascending=False)

print(opportunities.to_string(index=False))
opportunities.to_csv("striking_distance.csv", index=False)

The script renames the columns on the way in, because the export uses labels such as “Top queries” and stores CTR as text with a percent sign. Converting CTR to a number lets you sort and filter on it. If your Search Console interface is in another language, the column labels change but the order stays the same, which is why the script assigns names by position.

Adjust the two thresholds to your site. A small local business might use 50 impressions instead of 500. A large store might narrow the range to positions 5 to 12. For each query in the output, find the ranking page, then check whether the query is actually answered in the title, the H1 and the first paragraphs.

A limit worth knowing: Google states that Search Console exports from the interface are truncated to 1,000 rows. For larger sites, the Search Console API returns up to 25,000 rows per request, and you can page through more using the startRow parameter. Setting up API access involves a Google Cloud project and credentials, which is a good second project once these scripts feel comfortable.

Example 4: how do you see which pages lost clicks between two periods?

This script compares two Pages exports from Search Console and lists the pages with the biggest drop in clicks, next to their average position before and after. It is the core of a monthly SEO check and much faster than matching rows by hand.

Export the Pages report twice: once for the recent period (saved as Pages_last.csv) and once for the previous period (Pages_prev.csv). Use periods of the same length, and if your business is seasonal, compare with the same weeks a year earlier.

import pandas as pd

cols = ["page", "clicks", "impressions", "ctr", "position"]
now = pd.read_csv("Pages_last.csv", names=cols, header=0)
before = pd.read_csv("Pages_prev.csv", names=cols, header=0)

merged = now.merge(before, on="page", how="outer", suffixes=("_now", "_before"))
merged[["clicks_now", "clicks_before"]] = merged[["clicks_now", "clicks_before"]].fillna(0).astype(int)
merged["click_change"] = merged["clicks_now"] - merged["clicks_before"]

losers = merged.sort_values("click_change").head(10)
print(losers[["page", "clicks_before", "clicks_now", "click_change",
              "position_before", "position_now"]].to_string(index=False))

The outer merge matters. A page that disappeared from the recent export shows clicks_now as 0 and position_now as empty, which is exactly the kind of page you want to catch. A page that is new appears with clicks_before as 0. A plain spreadsheet lookup often hides both cases.

Read the output in pairs. Lost clicks with a worse position point to a ranking problem: check the page, its competitors and any recent changes. Lost clicks with a stable position usually mean fewer searches or a changed results page, for example a new AI Overview or more ads. Our guide to tracking SEO results covers how to separate those causes.

Which SEO tasks should you script next, and which should you leave to tools?

Script tasks that are specific to your site or your reporting; buy tools for tasks that need scale or infrastructure.

Script it yourself or use a dedicated tool?
TaskPython scriptDedicated tool
Status codes for a known URL listYes, simple and fastAlso fine in any crawler
Full site crawl with renderingPossible, but slow to buildBetter: crawler software
Custom Search Console reportsYes, ideal with pandasLooker Studio for dashboards
Joining data from several toolsYes, pandas merge on URLSpreadsheets struggle at scale
Rank tracking over timeNot recommendedBetter: rank tracker
Grouping keywords by topicYes, with an AI assistant’s helpSome platforms include it
Backlink dataOnly through a paid APIBetter: backlink tool

Good next projects: grouping queries by a word they contain, such as “price” or a city name, and joining Search Console page data with GA4 conversions on the URL.

How do you use AI assistants to understand code, not only write it?

Ask for explanations at the level you need, then test your understanding by changing one thing. Paste a script and ask: “Explain this line by line for someone who knows Excel but not Python.” Then ask a specific question, such as “What would I change to also extract the H1?”, and make the change yourself before asking for the answer.

The most valuable follow-up is “What could make this script give wrong results without an error?” It pushes the assistant to list silent failure modes, such as wrong encoding, duplicated rows or a filter that removes more than you expect.

When does it make sense to bring in Marketer Coffee?

Scripts answer questions; they do not decide which questions matter. Marketer Coffee is an AI SEO and GEO agency, and we use this kind of automation inside larger projects: technical clean-ups, content programs and AI visibility work. Two results from our clients, in industries unrelated to this guide’s examples:

  • Aldi.pl (retail). Organic clicks grew from 367,127 to 852,724 a month in 12 months (+132%) through product content, Product schema, a leaner architecture and unified store data. Read the Aldi case study.
  • Planika (design fireplaces). Seven US-localized articles took a site Google had not indexed to 1,052 monthly US visits, with Ahrefs recording 401 Google AI Overview mentions, 136 Perplexity mentions and 20 ChatGPT mentions. Read the Planika case study.

Who we fit: companies with large or international sites where data work, content and AI search need one plan. Who we do not fit: anyone who only needs a single script written; an AI assistant and this guide will serve you better and cost nothing.

If you want to see how AI engines currently describe your site, run our free AI visibility audit. More on the service on our AI SEO page.

Frequently asked questions about Python for SEO

Is Python worth learning for SEO in 2026?

Yes, at a basic level. With ChatGPT or Claude writing most of the code, the value lies in knowing what to ask for and how to check the result. A few evenings of practice are enough to automate status checks, metadata audits and Search Console reports.

Can ChatGPT or Claude write SEO scripts that work on the first try?

Often, if you describe the input file, the output columns and the edge cases. Always test on a small sample where you know the answer, and paste the full error message back to the assistant if something fails.

Which Python libraries should an SEO beginner learn first?

requests for fetching pages, Beautiful Soup for reading HTML, and pandas for working with CSV and spreadsheet data. These three cover most beginner SEO scripts.

How do I get more than 1,000 rows from Search Console?

The interface export is truncated to 1,000 rows. The Search Console API returns up to 25,000 rows per request and supports paging with startRow, so a Python script using the API can pull much larger datasets.

Is it safe to run SEO scripts against any website?

Run them on sites you own or have permission to test, keep request volume modest, set a timeout, and add pauses for large lists. Never share API keys or client data in an AI chat.

What should you remember about Python for SEO?

Start small, test on data you know and let the AI assistant do the typing while you do the thinking. The four scripts in this guide cover the most common beginner needs: status codes, metadata, striking distance queries and period comparisons. Each one replaces a recurring spreadsheet task and can be extended one prompt at a time.

If you would rather have a team that combines this kind of analysis with content and AI search strategy, Book a free consultation.

Sources: Google Search Console Help, “Export data directly from a Search Console report” (1,000-row export limit); Google for Developers, Search Console API, Search Analytics: query reference (rowLimit 1 to 25,000, startRow); requests, Beautiful Soup and pandas official documentation; scripts tested by Marketer Coffee on sample data with Python 3.13 (November 2026); Marketer Coffee, Aldi and Planika case studies (other industries).

Leave a Reply

Your email address will not be published. Required fields are marked *

Want results like these for your site?

Book a free 30-minute call. You leave with three concrete SEO opportunities, whether we work together or not.

Book a free call