Step-by-Step Guide: Google Analytics SEO Analysis with Python and OpenAI

 

 

 

This guide will show you how to implement a Python script that connects to Google Analytics 4 (GA4), fetches analytics data, and generates SEO insights using OpenAI. Follow these steps to set up, authenticate, and run the script seamlessly.


1. Prerequisites

Ensure you have the following before starting:

  • A Google Analytics 4 (GA4) property with access permissions.
  • A Google Cloud Platform (GCP) project with API access enabled.
  • A Python 3 environment installed on your machine.
  • An OpenAI API key.

2. Set Up Google Cloud Platform

a. Create a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click on Create Project and name it.
  3. Note the Project ID for later use.

b. Enable the Google Analytics Data API

  1. Open the API Library.
  2. Search for Google Analytics Data API and click Enable.

c. Create a Service Account

  1. Go to IAM & Admin → Service Accounts.
  2. Create a new Service Account and assign it the Viewer role.
  3. Generate a JSON key by navigating to the Keys tab and clicking Create New Key.
  4. Save the JSON file securely.

d. Grant Access to the Service Account in Google Analytics

  1. Go to your GA4 property and navigate to Admin → Account Access Management.
  2. Add the service account email as a user with the Viewer role.

3. Set Up Your Environment

a. Install Python Libraries

Run the following command in your terminal:

pip install google-analytics-data openai

b. Prepare Your Environment

  • Save the JSON key file downloaded from Google Cloud to a known location (e.g., path/to/your-service-account.json).
  • Obtain your OpenAI API Key from OpenAI’s API Dashboard.

4. The Python Script

Below is the complete script. Replace placeholders like path/to/your-service-account.json and your_openai_api_key with your actual details.

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Metric, Dimension, RunReportRequest
import openai
# Set your OpenAI API key
openai.api_key = "your_openai_api_key"
# Set up Google Analytics API client
def initialize_analytics_client():
    client = BetaAnalyticsDataClient.from_service_account_json(
        "path/to/your-service-account.json"
    )
    return client
# Fetch analytics data
def fetch_analytics_data(client, property_id):
    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="pagePath"), Dimension(name="country")],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="sessions"),
            Metric(name="bounceRate"),
            Metric(name="averageSessionDuration")
        ],
        date_ranges=[DateRange(start_date="30daysAgo", end_date="today")],
    )
    response = client.run_report(request)
    
    # Parse data into a readable format
    data = []
    for row in response.rows:
        data.append(
            [dimension_value.value for dimension_value in row.dimension_values] +
            [metric_value.value for metric_value in row.metric_values]
        )
    return data
# Generate SEO insights using OpenAI
def summarize_data_with_chatgpt(data):
    data_text = "\n".join([", ".join(row) for row in data])
    prompt = f\"\"\"
    You are an expert SEO and web analytics consultant. Analyze the Google Analytics data below and provide actionable SEO insights.
    Data:
    {data_text}
    \"\"\"
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a data and SEO expert."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=2000
    )
    return response['choices'][0]['message']['content']
if __name__ == "__main__":
    property_id = "your_ga4_property_id"
    client = initialize_analytics_client()
    analytics_data = fetch_analytics_data(client, property_id)
    seo_summary = summarize_data_with_chatgpt(analytics_data)
    print("SEO Summary and Recommendations:")
    print(seo_summary)

5. Run the Script

  1. Save the script as analytics_seo_analysis.py.
  2. Run it in your terminal or Python IDE:
python analytics_seo_analysis.py

6. Customize as Needed

  • Modify dimensions and metrics to match your analytics goals.
  • Adjust the prompt for specific SEO analysis tasks.
  • Split large datasets into smaller chunks if they exceed token limits.

And that’s it! You now have a working Python script to analyze Google Analytics data and generate actionable SEO recommendations using OpenAI. Happy coding![/et_pb_text][/et_pb_column]
[/et_pb_row]
[/et_pb_section]