如何通过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()
关键说明
- 自定义参数的维度命名规则:GA4事件级自定义参数在Data API中需使用
eventParam:参数名的格式,若为用户级自定义维度则使用userProperty:参数名。 - 数据可用性:确保自定义参数
n20_page_url已正确关联到page_view事件,且GA4已完成数据采集处理(通常需等待24小时)。 - 指标与维度扩展:可根据需求添加其他内置维度(如
pageTitle)或指标(如activeUsers),调整dimensions和metrics列表即可。
内容的提问来源于stack exchange,提问作者M B
相关产品推荐
相关产品推荐

