You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python调用Google Analytics API获取GA4自定义参数数据

GA4自定义维度数据的Python获取方案

问题描述

我在GA4中为page_view事件定义了自定义参数n20_page_url,需要通过Python获取每日该参数对应的页面访问数据(包含日期、页面URL、事件计数、总用户数)。现有代码仅能获取内置维度和指标,无法读取自定义参数数据。

已安装依赖库:

pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-analytics-data

原代码:

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    RunReportRequest,
)
from google.oauth2 import service_account

import globals

SCOPES = globals.SCOPES
KEY_FILE_LOCATION = globals.KEY_FILE_LOCATION
PROPERTY_ID = globals.PROPERTY_ID

def sample_run_report():
 
    property_id = PROPERTY_ID

    credentials = service_account.Credentials.from_service_account_file(
        KEY_FILE_LOCATION, scopes=SCOPES)

    client = BetaAnalyticsDataClient(credentials=credentials)
    request = RunReportRequest(
        property=f"properties/{PROPERTY_ID}",
        dimensions=[{"name": "date"}],
        metrics=[{"name": "activeUsers"}],
        date_ranges=[{"start_date": "7daysAgo", "end_date": "today"}]
    )
    response = client.run_report(request)
    print("Report result:")
    for row in response.rows:
        print(row.dimension_values[0].value, row.metric_values[0].value)

if __name__ == "__main__":
    sample_run_report()

修改后的代码

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    RunReportRequest,
)
from google.oauth2 import service_account

import globals

SCOPES = globals.SCOPES
KEY_FILE_LOCATION = globals.KEY_FILE_LOCATION
PROPERTY_ID = globals.PROPERTY_ID

def sample_run_report():
    credentials = service_account.Credentials.from_service_account_file(
        KEY_FILE_LOCATION, scopes=SCOPES)

    client = BetaAnalyticsDataClient(credentials=credentials)
    request = RunReportRequest(
        property=f"properties/{PROPERTY_ID}",
        # 包含日期和自定义事件参数作为维度
        dimensions=[
            {"name": "date"},
            {"name": "eventParam:n20_page_url"}
        ],
        # 按需指定指标:事件计数、总用户数
        metrics=[
            {"name": "eventCount"},
            {"name": "totalUsers"}
        ],
        date_ranges=[{"start_date": "7daysAgo", "end_date": "today"}],
        # 按日期和页面URL排序,优化数据展示
        order_bys=[
            {"dimension": {"dimension_name": "date"}},
            {"dimension": {"dimension_name": "eventParam:n20_page_url"}}
        ]
    )
    response = client.run_report(request)
    
    # 格式化输出表头和数据
    print("日期 | 页面URL | 事件计数 | 总用户数")
    print("--- | --- | --- | ---")
    for row in response.rows:
        date = row.dimension_values[0].value
        page_url = row.dimension_values[1].value
        event_count = row.metric_values[0].value
        total_users = row.metric_values[1].value
        print(f"{date} | {page_url} | {event_count} | {total_users}")

if __name__ == "__main__":
    sample_run_report()

关键说明

  1. 自定义参数的维度命名规则:GA4事件级自定义参数在Data API中需使用eventParam:参数名的格式,若为用户级自定义维度则使用userProperty:参数名。
  2. 数据可用性:确保自定义参数n20_page_url已正确关联到page_view事件,且GA4已完成数据采集处理(通常需等待24小时)。
  3. 指标与维度扩展:可根据需求添加其他内置维度(如pageTitle)或指标(如activeUsers),调整dimensions和metrics列表即可。

内容的提问来源于stack exchange,提问作者M B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 08:17:45