GA API是Google Analytics API的缩写,它是一组用于访问和管理Google Analytics数据的开发工具。使用GA API可以搜索UTM参数,以下是如何使用GA API搜索UTM参数的步骤:
import google.auth
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from googleapiclient.discovery import build
# 加载密钥文件
credentials = service_account.Credentials.from_service_account_file(
'path/to/your/keyfile.json',
scopes=['https://www.googleapis.com/auth/analytics.readonly']
)
# 创建API客户端
service = build('analyticsreporting', 'v4', credentials=credentials)
# 构建请求
request = {
'viewId': 'your-view-id',
'dateRanges': [{'startDate': '2022-01-01', 'endDate': '2022-01-31'}],
'dimensions': [{'name': 'ga:sourceMedium'}, {'name': 'ga:campaign'}, {'name': 'ga:keyword'}],
'metrics': [{'expression': 'ga:sessions'}],
'filtersExpression': 'ga:medium==referral'
}
# 发送请求并获取响应
response = service.reports().batchGet(body={'reportRequests': [request]}).execute()
# 处理响应数据
for report in response['reports']:
columnHeader = report['columnHeader']
dimensionHeaders = columnHeader['dimensions']
metricHeaders = columnHeader['metricHeader']['metricHeaderEntries']
rows = report['data']['rows']
for row in rows:
dimensions = row['dimensions']
metrics = row['metrics']
for i, dimension in enumerate(dimensions):
print(dimensionHeaders[i] + ': ' + dimension)
for metric in metrics:
values = metric['values']
for j, value in enumerate(values):
print(metricHeaders[j]['name'] + ': ' + value)
在上述代码中,你需要替换以下内容:
'path/to/your/keyfile.json'
:为你的JSON密钥文件的路径。'your-view-id'
:为你的Google Analytics视图ID。'2022-01-01'
和'2022-01-31'
:为你要搜索的日期范围。领取专属 10元无门槛券
手把手带您无忧上云