Technical SEO

How to Use Claude AI for SEO Automation: Scripts, Workflows, and Real Examples

· · 16 min read

Most SEO work is not strategy. It is repetitive, rule-based execution: generating meta descriptions for 200 pages, validating structured data across a site, building redirect maps during a migration. These tasks eat hours every week, and they follow patterns that a capable AI can handle.

Claude AI changes the equation for SEO practitioners because it does not just chat about SEO concepts — it writes working code. You can hand it a CSV of URLs and get back a Python script that generates optimised meta tags with character-count validation. You can describe a schema requirement and receive valid JSON-LD. You can use Claude Code directly in your terminal to audit heading structures across an entire site.

According to Marketer Milk’s 2026 SEO automation tools review, one practitioner’s production time dropped from 8 hours to 3 hours per landing page after adopting automation workflows. That is a 62% reduction — and the article’s author was still writing all the content himself. The time savings came entirely from automating the surrounding tasks: keyword analysis, outline generation, formatting, and metadata creation.

62%
less production time per page after automating the surrounding workflow
Source: Marketer Milk — 8 hours down to 3, still writing every article by hand
~10 min
saved per page on metadata generation alone
Source: Search Engine Land
1 hour
saved per 100 rows of SEO data validated
Source: Search Engine Land
The time savings come from automating execution — metadata, validation, formatting — not the writing or the strategy.

This guide takes a different approach from every other SEO automation article on the web. Instead of listing tools and conceptual advice, it gives you working code you can copy and run today.

Key takeaways

  • Claude AI reduces SEO busywork by generating working Python scripts, JSON-LD schemas, and CLI commands you can run immediately — no competitor article includes actual code.
  • Metadata automation alone saves approximately 10 minutes per page according to Search Engine Land’s SEO automation guide, compounding significantly across large sites.
  • Claude Code CLI lets you run technical SEO audits directly from your terminal without switching between browser-based tools.
  • Automating structured data generation eliminates the most common source of schema validation errors: manual JSON-LD formatting.
  • The hybrid approach works best — automate repetitive execution tasks, keep human judgment for strategy and editorial decisions.

Why SEO practitioners are turning to Claude AI

SEO involves dozens of tasks that follow predictable patterns. Writing meta descriptions is a formula: include the primary keyword, stay under 160 characters, end with a reason to click. Generating FAQ schema is mechanical: extract questions, pair them with answers, wrap them in JSON-LD. Checking heading hierarchy is rule-based: one H1, properly nested H2s and H3s, no skipped levels.

These are exactly the kinds of tasks where Claude AI excels. Unlike generic chatbots that produce vague recommendations, Claude can generate syntactically valid code, follow strict output constraints, and process structured data. When you need a Python script that reads a CSV and outputs formatted meta tags, Claude produces code you can run directly — not pseudocode you need to rewrite.

The time savings are substantial across the full workflow. Data validation alone saves roughly 1 hour per 100 rows of SEO data according to Search Engine Land’s data validation time estimates. Multiply that across keyword research, competitor analysis, and reporting, and the hours reclaimed per week become significant.

What makes Claude particularly well-suited for SEO automation is its extended context window. You can feed it an entire site’s worth of URLs, title tags, and meta descriptions in a single prompt, then ask it to identify patterns, flag issues, and generate replacements. You are not limited to one-page-at-a-time workflows.

Automating meta tag generation with Python and Claude

Meta tag creation is the ideal first automation target. The rules are clear, the output is structured, and the quality is easy to validate. Here is a complete Python script that uses the Anthropic API to batch-generate meta titles and descriptions.

The complete Python script

import anthropic
import csv
import json
import sys


def generate_meta_tags(input_csv: str, output_csv: str, primary_keyword: str) -> None:
    """Generate SEO meta titles and descriptions for a batch of URLs."""
    client = anthropic.Anthropic()

    with open(input_csv, newline="", encoding="utf-8") as infile:
        reader = csv.DictReader(infile)
        rows = list(reader)

    results = []
    for row in rows:
        url = row["url"]
        page_title = row.get("current_title", "")
        page_content_snippet = row.get("content_snippet", "")

        prompt = f"""Generate an SEO-optimised meta title and meta description for this page.

URL: {url}
Current title: {page_title}
Content snippet: {page_content_snippet}
Primary keyword: {primary_keyword}

Requirements:
- Meta title: max 60 characters, include the primary keyword near the start
- Meta description: 140-160 characters, include the primary keyword naturally, end with a reason to click
- Use British English spelling

Return JSON only:
{{"meta_title": "...", "meta_description": "..."}}"""

        message = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=256,
            messages=[{"role": "user", "content": prompt}],
        )

        try:
            response_text = message.content[0].text
            meta = json.loads(response_text)
            meta["url"] = url
            meta["title_length"] = len(meta["meta_title"])
            meta["description_length"] = len(meta["meta_description"])
            results.append(meta)
        except (json.JSONDecodeError, IndexError, KeyError) as exc:
            results.append({
                "url": url,
                "meta_title": "",
                "meta_description": "",
                "error": str(exc),
            })

    with open(output_csv, "w", newline="", encoding="utf-8") as outfile:
        fieldnames = [
            "url", "meta_title", "title_length",
            "meta_description", "description_length", "error",
        ]
        writer = csv.DictWriter(outfile, fieldnames=fieldnames, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(results)

    print(f"Generated meta tags for {len(results)} URLs -> {output_csv}")


if __name__ == "__main__":
    generate_meta_tags(
        input_csv=sys.argv[1] if len(sys.argv) > 1 else "urls.csv",
        output_csv=sys.argv[2] if len(sys.argv) > 2 else "meta_tags.csv",
        primary_keyword=sys.argv[3] if len(sys.argv) > 3 else "seo automation",
    )

This script reads a CSV with columns url, current_title, and content_snippet, sends each row to Claude with strict formatting constraints, and writes the results to a new CSV with character counts included.

Validating output length and keyword placement

After generating the meta tags, you need to validate that they meet SEO requirements. Automating this post-generation check catches issues before they reach your CMS. According to Search Engine Land’s SEO automation guide, metadata automation saves approximately 10 minutes per page — and that estimate assumes manual validation. With programmatic validation, the savings compound further.

import csv
from dataclasses import dataclass


@dataclass
class ValidationResult:
    url: str
    title_ok: bool
    description_ok: bool
    keyword_in_title: bool
    keyword_in_description: bool
    issues: list[str]


def validate_meta_tags(
    csv_path: str,
    primary_keyword: str,
    max_title_length: int = 60,
    min_desc_length: int = 140,
    max_desc_length: int = 160,
) -> list[ValidationResult]:
    """Validate generated meta tags against SEO requirements."""
    results = []

    with open(csv_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            issues = []
            title = row.get("meta_title", "")
            desc = row.get("meta_description", "")
            keyword_lower = primary_keyword.lower()

            title_ok = 0 < len(title) <= max_title_length
            if not title_ok:
                issues.append(f"Title length {len(title)} exceeds {max_title_length}")

            desc_ok = min_desc_length <= len(desc) <= max_desc_length
            if not desc_ok:
                issues.append(
                    f"Description length {len(desc)} outside "
                    f"{min_desc_length}-{max_desc_length} range"
                )

            keyword_in_title = keyword_lower in title.lower()
            if not keyword_in_title:
                issues.append("Primary keyword missing from title")

            keyword_in_description = keyword_lower in desc.lower()
            if not keyword_in_description:
                issues.append("Primary keyword missing from description")

            results.append(ValidationResult(
                url=row["url"],
                title_ok=title_ok,
                description_ok=desc_ok,
                keyword_in_title=keyword_in_title,
                keyword_in_description=keyword_in_description,
                issues=issues,
            ))

    passed = sum(1 for r in results if not r.issues)
    print(f"Validation: {passed}/{len(results)} pages passed all checks")
    return results

Run the generator first, then pipe the output through the validator. Any page that fails gets flagged with specific issues you can address in a second pass.

Generating JSON-LD structured data with Claude

Structured data is where manual SEO work produces the most errors. A misplaced comma in JSON-LD breaks the entire schema. A missing required field causes Google to ignore it silently. Automating schema generation eliminates these formatting errors entirely.

FAQPage schema from existing content

The following script takes a markdown file containing FAQ headings and answers, then generates valid FAQPage JSON-LD. You can adapt it to pull from your CMS, a Google Doc, or any structured text source.

import json
import re


def extract_faqs_from_markdown(markdown_text: str) -> list[dict]:
    """Extract Q&A pairs from markdown H3 headings that end with '?'."""
    faq_pattern = re.compile(
        r"^###\s+(.+\?)\s*\n\n((?:(?!^##)[\s\S])*?)(?=\n^##|\n^###|\Z)",
        re.MULTILINE,
    )
    faqs = []
    for match in faq_pattern.finditer(markdown_text):
        question = match.group(1).strip()
        answer = match.group(2).strip()
        answer = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", answer)
        answer = re.sub(r"\s+", " ", answer)
        if question and answer:
            faqs.append({"question": question, "answer": answer})
    return faqs


def build_faq_schema(faqs: list[dict]) -> dict:
    """Build a valid FAQPage JSON-LD schema from Q&A pairs."""
    return {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": [
            {
                "@type": "Question",
                "name": faq["question"],
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": faq["answer"],
                },
            }
            for faq in faqs
        ],
    }


if __name__ == "__main__":
    sample_markdown = """
### Is Claude better than ChatGPT for SEO automation?

Claude excels at structured output and code generation, which makes it
well-suited for SEO tasks that require valid JSON, CSV processing, or
Python scripts. ChatGPT is stronger for conversational research and
brainstorming. The best choice depends on whether your workflow is
code-heavy or conversation-heavy.

### How much does it cost to automate SEO with Claude?

The Anthropic API charges per million tokens. A typical meta tag
generation batch of 100 pages costs under two dollars in API calls.
Claude Code subscriptions start at twenty dollars per month for
individual use.
"""
    faqs = extract_faqs_from_markdown(sample_markdown)
    schema = build_faq_schema(faqs)
    print(json.dumps(schema, indent=2))

Running this script produces clean, valid JSON-LD that you can paste directly into your page’s <head> section:

{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Is Claude better than ChatGPT for SEO automation?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Claude excels at structured output and code generation, which makes it well-suited for SEO tasks that require valid JSON, CSV processing, or Python scripts. ChatGPT is stronger for conversational research and brainstorming. The best choice depends on whether your workflow is code-heavy or conversation-heavy."
      }
    },
    {
      "@type": "Question",
      "name": "How much does it cost to automate SEO with Claude?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "The Anthropic API charges per million tokens. A typical meta tag generation batch of 100 pages costs under two dollars in API calls. Claude Code subscriptions start at twenty dollars per month for individual use."
      }
    }
  ]
}

Article schema with author and publisher markup

Beyond FAQ schema, you can generate Article structured data with author and publisher markup. This is the kind of schema that most content teams create manually — and consistently get wrong.

import json
from datetime import datetime


def build_article_schema(
    title: str,
    description: str,
    url: str,
    author_name: str,
    publisher_name: str,
    publisher_url: str,
    date_published: str | None = None,
    date_modified: str | None = None,
    image_url: str | None = None,
) -> dict:
    """Build a valid Article JSON-LD schema."""
    schema = {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": title[:110],
        "description": description[:160],
        "url": url,
        "author": {
            "@type": "Person",
            "name": author_name,
        },
        "publisher": {
            "@type": "Organization",
            "name": publisher_name,
            "url": publisher_url,
        },
        "datePublished": date_published or datetime.now().strftime("%Y-%m-%d"),
        "dateModified": date_modified or datetime.now().strftime("%Y-%m-%d"),
    }
    if image_url:
        schema["image"] = image_url
    return schema


if __name__ == "__main__":
    schema = build_article_schema(
        title="How to Use Claude AI for SEO Automation",
        description="Learn how to automate SEO tasks with Claude AI using Python scripts and CLI workflows.",
        url="https://nadiamohamed.me/insights/claude-ai-seo-automation/",
        author_name="Nadia Mohamed",
        publisher_name="Nadia Mohamed",
        publisher_url="https://nadiamohamed.me",
        date_published="2026-06-23",
    )
    print(json.dumps(schema, indent=2))

The function enforces Google’s requirements: headline truncated to 110 characters, description to 160 characters, and proper @type annotations for author and publisher entities.

Claude Code CLI for SEO: terminal-based automation

Claude Code is Anthropic’s command-line tool that runs directly in your terminal. It can read files, execute scripts, browse the web, and interact with your project files. For SEO practitioners who are comfortable in the terminal, it is the fastest path from question to answer.

Heading structure audit from the terminal

You can run a complete heading hierarchy audit on any HTML file with a single command. Brief creation automation typically saves about 20 minutes per ticket according to Search Engine Land’s brief creation time savings, and terminal-based workflows compress that further by eliminating context-switching between browser tools.

# Audit heading structure of a local HTML file
claude -p "Read index.html and check the heading hierarchy.
Report: number of H1 tags (should be exactly 1),
whether H2/H3/H4 tags are properly nested (no skipped levels),
and list any headings that are empty or duplicated.
Output as a markdown table."

# Audit heading structure of a live URL (requires curl)
curl -s https://example.com | claude -p "Analyse this HTML.
Check the heading hierarchy: count H1 tags, verify nesting,
flag empty or duplicate headings. Output as a markdown table."

# Batch audit multiple pages from a URL list
while IFS= read -r url; do
  echo "=== $url ==="
  curl -s "$url" | claude -p "Check heading hierarchy. Report issues only."
done < urls.txt

These commands give you an instant technical audit without opening a browser, navigating to a tool, and pasting URLs one at a time.

Bulk redirect map generation

Site migrations are one of the most error-prone SEO tasks. Generating a redirect map from a spreadsheet of old and new URLs is tedious and repetitive. Claude Code handles it directly.

# Generate a redirect map from a CSV with old_url and new_url columns
claude -p "Read migration-urls.csv (columns: old_url, new_url).
Generate an nginx redirect map in the format:
rewrite ^/old-path$ /new-path permanent;
Skip any rows where old_url equals new_url.
Save the output to redirects.conf"

# Generate Apache .htaccess redirects instead
claude -p "Read migration-urls.csv and generate Apache 301 redirects:
Redirect 301 /old-path https://example.com/new-path
Save to .htaccess"

The key advantage here is that Claude Code can read your actual files, validate the URLs, and write the output file — all within a single command. You do not need to copy data between applications.

Automating keyword analysis and content briefs

Keyword research itself requires human judgment — understanding search intent, evaluating business relevance, and making strategic decisions about which terms to target. But the analysis that follows keyword selection is largely mechanical, and that is where automation delivers the most value.

According to Search Engine Land’s task automation breakdown, keyword research automation saves approximately 15 minutes per page. Content calendar planning saves 8 hours per quarter according to Search Engine Land’s 2026 automation analysis. Both tasks involve processing structured data against known rules — exactly what a script handles well.

The following Python script takes a list of keywords and uses Claude to classify them by search intent, then groups them into content clusters.

import anthropic
import json


def cluster_keywords_by_intent(keywords: list[str]) -> dict:
    """Use Claude to classify keywords by search intent and cluster them."""
    client = anthropic.Anthropic()

    prompt = f"""Classify each keyword by search intent and group them into content clusters.

Keywords:
{json.dumps(keywords, indent=2)}

For each keyword, determine:
1. Intent: informational, navigational, commercial, or transactional
2. Cluster: group keywords that could be targeted by the same page

Return valid JSON:
{{
  "clusters": [
    {{
      "cluster_name": "descriptive name",
      "intent": "informational",
      "keywords": ["keyword1", "keyword2"],
      "suggested_page_type": "guide | comparison | landing page | blog post"
    }}
  ]
}}"""

    message = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )

    return json.loads(message.content[0].text)


if __name__ == "__main__":
    sample_keywords = [
        "claude ai for seo",
        "best seo automation tools",
        "how to automate meta descriptions",
        "seo automation software pricing",
        "automate technical seo audit",
        "claude code seo workflow",
    ]
    result = cluster_keywords_by_intent(sample_keywords)
    print(json.dumps(result, indent=2))

This script gives you a structured starting point for content planning. The clusters are suggestions — you apply your own knowledge of search intent and competitive landscape to refine them. The automation removes the manual sorting work, not the strategic decision-making.

For those who prefer working from the terminal, you can also integrate this with your existing SEO tools. If you want a deeper look at how to connect keyword data pipelines with content planning, see our SEO for engineers guide.

What you should not automate with AI

Not every SEO task benefits from automation. Some tasks require contextual judgment that AI consistently gets wrong, and automating them creates more work than it saves.

Link building strategy requires relationship-building, editorial judgment, and an understanding of your industry’s social dynamics. AI can draft outreach emails, but it cannot evaluate whether a site is worth pursuing or build genuine editorial relationships.

Content strategy decisions depend on business context that AI does not have. Which topics align with your revenue goals? Which keywords match your audience’s buying stage? These require human judgment informed by business data, not pattern matching.

Brand voice development is inherently subjective. AI can mimic a voice once defined, but defining what your brand sounds like requires creative judgment and stakeholder alignment.

The most effective approach is hybrid. Automate the execution layer: metadata generation, schema markup, heading audits, redirect maps, data validation. Keep human judgment on the strategy layer: which keywords to target, what content to create, how to position against competitors.

Internal linking is a good example of where the boundary falls. Automating link suggestions saves approximately 10 minutes per page according to Search Engine Land’s internal linking automation findings. But deciding which pages to prioritise for internal links, and how to structure the link topology for crawl efficiency, requires an understanding of your site’s information architecture that AI does not yet have.

Content freshness is another area where automation helps with detection but not decision-making. LLMs favour freshness signals, and content should be refreshed every 1-2 years according to Search Engine Land’s content freshness analysis. You can automate the detection of stale content — but deciding what to update and how to update it requires editorial judgment.

For more on building AI-assisted content workflows that balance automation with editorial quality, see our guide to AI content optimisation.

Getting started: your first Claude SEO automation

If you have never used Claude for SEO work, start with the smallest possible automation and expand from there.

Step 1: Install Claude Code. Open your terminal and run:

# Install Claude Code globally
npm install -g @anthropic-ai/claude-code

# Verify the installation
claude --version

# Start an interactive session
claude

Step 2: Run your first audit. Point Claude Code at one of your existing pages:

# Quick heading audit on a single page
curl -s https://yoursite.com/blog/example-post/ | \
  claude -p "Audit this page's SEO elements:
  1. Count H1 tags (should be exactly 1)
  2. Check heading nesting
  3. Check if meta description exists and its length
  4. List all internal links
  Output as a markdown checklist."

Step 3: Set up the Python environment. If you want to run the scripts from this guide:

# Create a virtual environment
python3 -m venv seo-automation
source seo-automation/bin/activate

# Install the Anthropic SDK
pip install anthropic

# Set your API key
export ANTHROPIC_API_KEY="your-key-here"

Step 4: Pick your first automation target. Start with the task you do most frequently. For most SEO practitioners, that is meta tag generation or schema markup. Run the Python scripts from the earlier sections on a small batch (10-20 pages) and validate the output before scaling.

The goal is not to automate everything on day one. It is to find the single repetitive task that takes the most time and build a reliable script for it. Once that script works consistently, move to the next task.

Frequently asked questions

Is Claude better than ChatGPT for SEO automation?

Claude and ChatGPT serve different strengths. Claude excels at structured output, code generation, and following strict formatting constraints — making it the stronger choice for tasks like meta tag generation, schema markup, and Python scripting. ChatGPT is stronger for conversational research, brainstorming, and its deep research feature for exploring topics. If your SEO automation workflow is code-heavy, Claude is the better fit. If it is research-heavy, ChatGPT may be more productive.

Can Claude Code replace SEO tools like Ahrefs or Semrush?

No. Claude Code processes and acts on data, but it does not collect the data itself. You still need Ahrefs for backlink analysis, keyword difficulty scores, and competitive research. You still need Semrush or Google Search Console for ranking data and traffic metrics. Claude Code sits on top of these tools — it automates the analysis and action steps that follow data collection.

How much does it cost to automate SEO with Claude?

The Anthropic API uses per-token pricing. Generating meta tags for 100 pages typically costs under two dollars in API calls using the Sonnet model. Claude Code subscriptions start at twenty dollars per month for individual use. Compared to hiring a virtual assistant or junior SEO specialist at fifteen to twenty-five dollars per hour, even moderate automation pays for itself within the first week of use.

Do I need to know Python to use Claude for SEO?

No. Claude Code works entirely from natural language commands in your terminal. You can audit headings, generate redirect maps, and check meta tags without writing a single line of code. However, Python unlocks batch processing, integration with external APIs, and repeatable pipelines. The scripts in this guide are designed to be copied and run directly — you do not need to understand every line to use them.