content writing ai automation, seo python developer, blogger laptop writing tools

Automating Content Writing and SEO with Python and AI

|

Learn how to build Python and AI tools that automatically generate SEO-optimized content, saving hours of manual work for every article you write.

Word Count: ~1900 · Reading Time: 10 minutes

Content and SEO Automation with Python and AI

Smart tools that generate search-engine-optimized content and save hours of manual work


Note to Reader: This article is completely standalone, and you can apply everything in it without reading previous posts. However, if you have not learned how to integrate AI models into Python yet, we recommend checking out our article: How to Use AI Models inside Your Python Projects.

Writing a single SEO-optimized article takes a professional blogger between three and five hours. This includes keyword research, drafting headlines, writing the content, editing, creating the Meta Description, and suggesting internal links. All of this happens before you even hit the publish button.

What if you could complete the mechanical part of this process—research, structuring, first drafting, and metadata—in minutes instead of hours? That is exactly what combining Python with Large Language Models (LLMs) allows you to do. In this article from ZY Yazan Platform, we will build an end-to-end tool to generate SEO-optimized content step-by-step, and learn how to integrate it into an actual daily workflow.

python web framework

 

What Can Actually Be Automated in Content Writing?

Before writing a single line of code, we must be honest about what automation can achieve and what it cannot. Automation is not magic that replaces the writer; it is a tool that frees them from repetitive, mechanical work, leaving more time for creative efforts.

Task Automatable? Note
Keyword Suggestions ✅ Yes — Fully Python + Search APIs
Article Structure & Headlines ✅ Yes — Fully LLMs excel at this
First Draft Content ⚡ Partially Always requires human review
Meta Data ✅ Yes — Fully Title, description, and tags in seconds
Internal Link Suggestions ✅ Yes — Fully From a spreadsheet/table of your existing posts
Personal Opinion & Real Experience ❌ No This is what separates one writer from another
Final Proofreading & Fact-Checking ❌ No Always a human responsibility

Step One: Automated Keyword Research

Before writing any article, a writer needs to know what their audience is actually searching for. We will use the DataForSEO API, or instead use a free analysis that relies on Google Autocomplete suggestions via Python:

import requests
import json
from openai import OpenAI
import os

client_ai = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

def get_google_suggestions(keyword: str, lang: str = "en") -> list[str]:
    """
    Fetch search suggestions from Google Autocomplete for free.
    Shows what people are actually searching for around a topic.
    """
    url = "http://suggestqueries.google.com/complete/search"
    params = {
        "client": "firefox",
        "q": keyword,
        "hl": lang,
    }
    try:
        response = requests.get(url, params=params, timeout=5)
        suggestions = response.json()[1]
        return suggestions[:10]
    except Exception:
        return []

def analyze_keywords_with_ai(seed_keyword: str) -> dict:
    """
    Analyzes suggested keywords and classifies them by search intent.
    """
    suggestions = get_google_suggestions(seed_keyword)
    suggestions_text = "\n".join(f"- {s}" for s in suggestions)

    prompt = f"""You are an SEO expert specialized in English content.
Base keyword: {seed_keyword}

Search engine suggestions:
{suggestions_text}

Analyze these words and output a JSON containing:
1. Top primary keywords (3 only)
2. Long-tail keywords (5 words)
3. Search Intent: Does the searcher want info, transactional, or navigational?
4. Competition level: easy/medium/hard

Respond with JSON only:
{{
  "primary_keywords": ["...", "...", "..."],
  "long_tail_keywords": ["...", "...", "...", "...", "..."],
  "search_intent": "informational/commercial/navigational",
  "competition_level": "easy/medium/hard",
  "recommendation": "One sentence explaining the optimal strategy"
}}"""

    response = client_ai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.2,
        response_format={"type": "json_object"}
    )
    return json.loads(response.choices[0].message.content)

# Testing the tool
result = analyze_keywords_with_ai("learn python for beginners")
print(json.dumps(result, indent=2))

Step Two: Generating the Article Outline

After selecting the keyword, we ask the AI to build a comprehensive article structure optimized for SEO from scratch:

def generate_article_outline(
    keyword: str,
    target_audience: str,
    word_count: int = 1500
) -> dict:
    """
    Creates a full outline for an SEO-optimized article.
    """
    prompt = f"""You are a professional writer and SEO specialist for English content.

Target Keyword: {keyword}
Target Audience: {target_audience}
Required Word Count: around {word_count} words

Create a comprehensive article outline that includes:
- An engaging H1 title containing the keyword (under 60 characters)
- An introduction summarizing what the reader will learn (4-5 sentences)
- 5 clear and logically structured H2 subheadings
- For each H2: an optional H3 subheading and two content points
- A conclusion with a Call to Action
- Meta Title (under 60 characters)
- Meta Description (between 120 and 155 characters)
- 5 suggested Tags

Respond with JSON only:
{{
  "h1_title": "...",
  "meta_title": "...",
  "meta_description": "...",
  "tags": ["...", "...", "...", "...", "..."],
  "introduction_summary": "...",
  "sections": [
    {{
      "h2": "...",
      "h3": "...",
      "key_points": ["...", "..."]
    }}
  ],
  "conclusion_cta": "..."
}}"""

    response = client_ai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.4,
        response_format={"type": "json_object"}
    )
    return json.loads(response.choices[0].message.content)

# Testing the tool
outline = generate_article_outline(
    keyword="best python libraries for freelancers",
    target_audience="freelancers who know HTML and are starting to learn Python",
    word_count=1500
)
print(f"Title: {outline['h1_title']}")
print(f"Meta Description: {outline['meta_description']}")

Step Three: Writing Article Sections Automatically

After obtaining the approved outline, we ask the model to write each section individually. Sectional writing is better than asking for the full article at once because it produces deeper, more focused content:

def write_section(
    section_title: str,
    key_points: list[str],
    keyword: str,
    section_index: int,
    total_sections: int,
    tone: str = "practical, clear, and engaging"
) -> str:
    """
    Writes a single section of the article based on the heading and specified points.
    """
    is_first = section_index == 0
    is_last = section_index == total_sections - 1

    context = ""
    if is_first:
        context = "This is the first section of the article — make the introduction compelling to keep the reader engaged."
    elif is_last:
        context = "This is the last section of the article — close with a practical summary and clear direction."

    prompt = f"""You are a professional technical writer. Write a section for an article about: {keyword}

Section Title: {section_title}
Core points to cover:
{chr(10).join(f'- {p}' for p in key_points)}

Required Style: {tone}
{context}

Instructions:
- Write in clear, standard English
- Use the pronoun "we" instead of "you"
- Include at least one practical example
- Do not mention the section title in the text — it will be added automatically
- Required length: 200-280 words

Write the text only without any comments or introduction."""

    response = client_ai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.6,
        max_tokens=600
    )
    return response.choices[0].message.content.strip()

def write_full_article(outline: dict, keyword: str) -> str:
    """
    Combines all sections into a complete HTML article.
    """
    sections = outline.get("sections", [])
    html_parts = []

    # Introduction
    intro = write_section(
        "Article Introduction",
        [outline.get("introduction_summary", "")],
        keyword,
        section_index=0,
        total_sections=len(sections)
    )
    html_parts.append(f"<p>{intro}</p>")

    # Main Sections
    for i, section in enumerate(sections):
        section_content = write_section(
            section["h2"],
            section.get("key_points", []),
            keyword,
            section_index=i,
            total_sections=len(sections)
        )
        html_parts.append(f'<h2 style="color: #c0392b;">{section["h2"]}</h2>\n<p>{section_content}</p>')
        
        if section.get("h3"):
            html_parts.append(f'<h3>{section["h3"]}</h3>')

    # Conclusion
    html_parts.append(f'<h2 style="color: #f5223b;">Conclusion</h2>\n<p>{outline.get("conclusion_cta", "")}</p>')

    return "\n\n".join(html_parts)

Step Four: Automated Quality and SEO Audit

Before publishing, we pass the article through an automated check that evaluates its SEO readiness and suggests improvements:

import re

def seo_quality_check(article_text: str, keyword: str, meta_description: str) -> dict:
    """
    Automated check for article quality from an SEO perspective.
    Pure programmatic rules—no AI API calls required.
    """
    word_count = len(article_text.split())
    keyword_count = article_text.lower().count(keyword.lower())
    keyword_density = round((keyword_count / word_count) * 100, 2) if word_count > 0 else 0

    # Calculate reading time (assuming 200 words/minute for English)
    reading_time = round(word_count / 200, 1)

    # Check Meta Description length
    meta_len = len(meta_description)
    meta_ok = 120 <= meta_len <= 155

    # Check for lists and subheadings
    has_lists = "<ul>" in article_text or "<ol>" in article_text
    h2_count = article_text.count("<h2")
    h3_count = article_text.count("<h3")

    issues = []
    suggestions = []

    if word_count < 1000:
        issues.append(f"The article is short ({word_count} words) — at least 1200 words is preferred")
    if keyword_density < 0.5:
        issues.append(f"Keyword density is low ({keyword_density}%) — 0.5%-1.5% is preferred")
    if keyword_density > 2.5:
        issues.append(f"Keyword density is high ({keyword_density}%) — risk of keyword stuffing")
    if not meta_ok:
        issues.append(f"Meta description ({meta_len} chars) is outside the ideal range (120-155 chars)")
    if h2_count < 3:
        suggestions.append("Add more H2 headings to improve structure")
    if not has_lists:
        suggestions.append("Add a bulleted or numbered list to improve readability")

    score = 100
    score -= len(issues) * 15
    score -= len(suggestions) * 5
    score = max(score, 0)

    return {
        "seo_score": score,
        "word_count": word_count,
        "reading_time_minutes": reading_time,
        "keyword_density_percent": keyword_density,
        "keyword_occurrences": keyword_count,
        "h2_count": h2_count,
        "h3_count": h3_count,
        "meta_description_length": meta_len,
        "issues": issues,
        "suggestions": suggestions,
        "status": "✅ Ready to Publish" if score >= 70 else "⚠️ Needs Improvement"
    }

Putting It All Together: Complete Workflow in One Function

Now we combine the four steps into a single integrated tool:

def full_content_pipeline(
    seed_keyword: str,
    target_audience: str,
    output_file: str = "article_output.html"
) -> None:
    """
    Complete workflow from seed keyword to a ready-to-publish HTML article.
    """
    print(f"\n🚀 Starting content production for: {seed_keyword}\n")

    # 1. Keyword Analysis
    print("📊 Step 1: Analyzing keywords...")
    kw_analysis = analyze_keywords_with_ai(seed_keyword)
    best_keyword = kw_analysis["primary_keywords"][0]
    print(f"   Selected keyword: {best_keyword}")

    # 2. Outline Generation
    print("📝 Step 2: Generating article outline...")
    outline = generate_article_outline(best_keyword, target_audience)
    print(f"   Title: {outline['h1_title']}")

    # 3. Article Writing
    print("✍️  Step 3: Writing article section by section...")
    article_html = write_full_article(outline, best_keyword)

    # 4. Quality Audit
    print("🔍 Step 4: Checking SEO quality...")
    quality = seo_quality_check(
        article_html,
        best_keyword,
        outline["meta_description"]
    )
    print(f"   SEO Score: {quality['seo_score']}/100 — {quality['status']}")
    if quality["issues"]:
        for issue in quality["issues"]:
            print(f"   ⚠️  {issue}")

    # 5. Save File
    wordpress_comment = f"""<!--
SEO Title: {outline['meta_title']}
Focus Keyword: {best_keyword}
Meta Excerpt: {outline['meta_description']}
WP Tags: {', '.join(outline['tags'])}
Slug: {seed_keyword.replace(' ', '-')}-en
-->"""

    final_output = f"{wordpress_comment}\n\n<article dir=\"ltr\" lang=\"en\">\n\n{article_html}\n\n</article>"

    with open(output_file, "w", encoding="utf-8") as f:
        f.write(final_output)

    print(f"\n✅ Completed! File saved to: {output_file}")
    print(f"   Word Count: {quality['word_count']}")
    print(f"   Reading Time: {quality['reading_time_minutes']} minutes\n")

# Run the entire pipeline
full_content_pipeline(
    seed_keyword="python libraries for freelancers",
    target_audience="web developers and bloggers learning Python",
    output_file="generated_article.html"
)

Practical Tips to Use the Tool Smartly

The tool we built is not a “click a button and get an article” solution. Instead, it is a “click a button and get a great draft that you finalize” system. Here is how professionals use it:

  • Use it for the first draft, not for direct publishing: AI produces an acceptable structure and content, but your personal voice and real experience are what actually make the article rank on search engines.
  • Always add information the model doesn’t know: Recent statistics, personal experiences, or a quote from an expert in your field—this is what sets you apart.
  • Do not publish the same content ten times: Search engines now detect repetitive and fully automated content. Diversity and customization are essential.
  • Use the tool to generate article ideas, not just full articles: Ask it for 20 article ideas in your niche, and pick the best ones to write yourself with deep insight.

Smart writers do not fear AI tools, nor do they delegate everything to them—they use them to multiply their productivity while maintaining their distinct voice.

content writing ai automation, seo python developer, blogger laptop writing tools


Conclusion and Next Step

Today we built a complete content production line that begins with a seed keyword and ends with an HTML file ready for publication, complete with an automated SEO assessment. The tool consists of four sequential phases: keyword analysis, outline generation, section writing, and quality check. Each phase is independent, and you can use any of them alone based on your needs.

Recommended Next Step:

We have mastered content writing and SEO optimization—but a true freelancer does not stop at a single tool. In the next article, we expand our horizons and build multiple smart tools that analyze competitors and generate tailored price quotes and business proposals for each client.

Join us for the fifteenth article: Building Your Own Smart Tools Using Python.


References and Sources:

  1. Google Search Engine Optimization Starter Guide: Google SEO Starter Guide
  2. Official OpenAI API Documentation: OpenAI API Documentation
  3. Backlinko Study on Content Length and Search Ranking: Backlinko — Google Ranking Factors

Similar Posts

Leave a Reply

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