Python Script

Automate Keyword Research with Python & the Google Ads API

In today's competitive landscape, a successful SEO strategy is built on data, not guesswork. Manually researching keywords is a time-consuming bottleneck. This guide provides a powerful Python script that automates this entire process, transforming your approach into a sophisticated, data-driven content strategy.

We will build a tool that connects directly to the Google Ads API—the ultimate source of truth for search data—to programmatically fetch search volume, competition levels, and CPC data for hundreds of keywords at once, exporting it all into a clean CSV report.

The Problem: Manual Research Doesn't Scale

Every great piece of content starts with understanding user intent, and that means keyword research. But the traditional process is painful: hours spent on manual entry, inconsistent data, and tedious copy-pasting. This approach is impossible to scale for modern strategies like programmatic SEO.

The Solution: A Python Automation Engine

By using Python and the official Google Ads API, we create an automation engine that provides:

How to Set Up and Run the Script

The Google Ads API is incredibly powerful, but requires a one-time setup process to gain access. This guide makes it easy.

  1. Prerequisites: You will need Python 3, pip, and an active Google Ads account.
  2. Google Ads API Credentials: This is the main setup step. You'll need to get a Developer Token, OAuth2 credentials (Client ID/Secret), and a Refresh Token, then place them in a `google-ads.yaml` file in your home directory.
  3. Install Dependencies: Open your terminal and run this command:
    pip install google-ads pandas
  4. Prepare Your Keywords: Create a file named `keywords.txt` and add all the keywords you want to analyze, one per line.
  5. Run the Automation: Execute the script from your terminal:
    python seo_keyword_tool.py
  6. Get Your Report: The script will generate a `keyword_report.csv` file in the same folder, ready for analysis.

import os
import pandas as pd
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

LOCATION_IDS = ["2840"]  # USA
LANGUAGE_ID = "1000"    # English

def get_keyword_metrics(client, customer_id, keywords):
    keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")
    request = client.get_type("GenerateKeywordIdeasRequest")
    request.customer_id = customer_id
    request.language = client.get_service("GoogleAdsService").language_constant_path(LANGUAGE_ID)
    request.geo_target_constants = [
        client.get_service("GoogleAdsService").geo_target_constant_path(loc_id)
        for loc_id in LOCATION_IDS
    ]
    request.keyword_seed.keywords.extend(keywords)
    request.historical_metrics_options.include_average_cpc = True

    try:
        print("Fetching keyword metrics from Google Ads API...")
        response = keyword_plan_idea_service.generate_keyword_ideas(request=request)
        
        results = []
        for idea in response.results:
            metrics = idea.keyword_idea_metrics
            competition = metrics.competition.name if metrics.competition else "UNKNOWN"
            results.append({
                "Keyword": idea.text,
                "Avg. Monthly Searches": metrics.avg_monthly_searches,
                "Competition": competition,
                "Low CPC ($)": metrics.low_top_of_page_bid_micros / 1_000_000 if metrics.low_top_of_page_bid_micros else 0,
                "High CPC ($)": metrics.high_top_of_page_bid_micros / 1_000_000 if metrics.high_top_of_page_bid_micros else 0,
            })
        return results
        
    except GoogleAdsException as ex:
        print(f'Request failed: {ex.error.code().name}')
        for error in ex.failure.errors:
            print(f'\tError: "{error.message}"')
        return None

def main():
    print("\n--- SEO Keyword Research Automation Tool ---")
    
    try:
        googleads_client = GoogleAdsClient.load_from_storage()
    except Exception as e:
        print(f"Failed to initialize Google Ads client. Ensure 'google-ads.yaml' is configured. Error: {e}")
        return

    customer_id = input("Enter your Google Ads Customer ID (e.g., 1234567890): ").strip().replace("-", "")
    
    keyword_file = "keywords.txt"
    if not os.path.exists(keyword_file):
        print(f"\nError: '{keyword_file}' not found. Please create it and add keywords.")
        return
        
    with open(keyword_file, 'r') as f:
        keywords = [line.strip() for line in f if line.strip()]
        
    if not keywords:
        print("Error: No keywords found in 'keywords.txt'.")
        return
        
    print(f"\nFound {len(keywords)} keywords to analyze.")

    keyword_data = get_keyword_metrics(googleads_client, customer_id, keywords)

    if keyword_data:
        df = pd.DataFrame(keyword_data)
        output_file = "keyword_report.csv"
        df.to_csv(output_file, index=False)
        print(f"\n\033[92mSuccess!\033[0m Report generated: {output_file}")
    else:
        print("\n\033[91mFailed to generate report.\033[0m")

if __name__ == "__main__":
    main()