Python Script

Unlock SEO Insights: Automate Keyword Research with Python & Google Ads API

In the competitive landscape of 2025, a successful SEO strategy is built on data, not guesswork. Manually researching keywords is a time-consuming bottleneck that limits your ability to scale. This guide provides a powerful Python script that automates this entire process, transforming your approach from manual labor to 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, and then export 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:

This approach is impossible to scale for modern strategies like programmatic SEO or comprehensive competitive intelligence.

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 (you don't need to be running ads).
  2. Google Ads API Credentials (The Hardest Part, Simplified):
    • Apply for a Developer Token from your Google Ads MCC account.
    • In the Google Cloud Console, create a project, enable the Google Ads API, and create OAuth2 credentials (Client ID and Client Secret).
    • Use Google's provided utility script to generate a Refresh Token.
    • Create a file named google-ads.yaml in your home directory and populate it with all these credentials. This is a one-time setup.
  3. Install Dependencies: Open your terminal and run this command:
    pip install google-ads pandas
  4. Prepare Your Keywords: In the same folder as your script, 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, containing all your keywords enriched with Google's data, ready for analysis in Excel or Google Sheets.

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

# --- Configuration ---
# Ensure your `google-ads.yaml` file is in your home directory.
# This script will automatically use it for authentication.
# For language and location targeting:
# Geo Target Constant IDs: https://developers.google.com/google-ads/api/reference/data/geotargets
# Language Constant IDs: https://developers.google.com/google-ads/api/reference/data/codes-formats#languages
LOCATION_IDS = ["2840"]  # USA
LANGUAGE_ID = "1000"    # English

def get_keyword_metrics(client, customer_id, keywords):
    """
    Fetches search volume and other metrics for a list of keywords.
    """
    keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")
    
    # Create the request object with our targeting and keywords
    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(location_id)
        for location_id in LOCATION_IDS
    ]
    request.keyword_seed.keywords.extend(keywords)
    request.historical_metrics_options.include_average_cpc = True # Include CPC data

    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 with ID "{ex.request_id}" failed with status "{ex.error.code().name}" and includes the following errors:')
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        return None

def main():
    print("\n--- SEO Keyword Research Automation Tool ---")
    
    # --- 1. Initialize Google Ads Client ---
    try:
        # The client will look for the `google-ads.yaml` in your home directory.
        googleads_client = GoogleAdsClient.load_from_storage()
    except Exception as e:
        print(f"Failed to initialize Google Ads client. Ensure 'google-ads.yaml' is configured correctly. Error: {e}")
        return

    # --- 2. Get Customer ID ---
    # This should be the ID of the Google Ads account you have API access to.
    # It should NOT have hyphens.
    customer_id = input("Enter your Google Ads Customer ID (e.g., 1234567890): ").strip().replace("-", "")
    
    # --- 3. Load Keywords from File ---
    keyword_file = "keywords.txt"
    if not os.path.exists(keyword_file):
        print(f"\nError: '{keyword_file}' not found. Please create it and add your keywords, one per line.")
        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.")

    # --- 4. Fetch Metrics and Generate Report ---
    keyword_data = get_keyword_metrics(googleads_client, customer_id, keywords)

    if keyword_data:
        # Use pandas to create a clean DataFrame and export to CSV
        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 Please check the error messages above.")

if __name__ == "__main__":
    main()