【发布时间】:2019-02-14 06:02:45
【问题描述】:
我一直试图调用谷歌分析核心报告 v4 来获取基本的流量数据,但我永远无法从 api 获得默认的频道分组/频道分组。但是,维度可以根据他们的metric and dimension explorer.
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = r"event-source.json"
VIEW_ID = 'xxxxxxx'
def initialize_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'pageSize': 10000,
'dateRanges': [{'startDate':'7daysago' , 'endDate': 'yesterday'}],
'metrics': [{'expression': 'ga:adCost'}],
'dimensions': [{'name':'ga:year'},{'name':'ga:month'},{'name':'ga:date'},{'name':'ga:channelGrouping'},
{'name':'ga:source'},{'name':'ga:medium'},{'name':'ga:campaign'},{'name':'ga:adGroup'},
{'name':'ga:keyword'},{'name':'ga:adContent'}],
'orderBys': [{"fieldName": "ga:date","sortOrder": "ASCENDING"}]
}]
}
).execute()
def print_response(response):
lst=[]
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
rows = report.get('data', {}).get('rows', [])
for row in rows:
dic={}
dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])
for header, dimension in zip(dimensionHeaders, dimensions):
dic[header] = dimension
for i, values in enumerate(dateRangeValues):
for metric, value in zip(metricHeaders, values.get('values')):
#set int as int, float a float
if ',' in value or ',' in value:
dic[metric.get('name')] = float(value)
else:
dic[metric.get('name')] = int(value)
lst.append(dic)
df=pd.DataFrame(lst)
return(df)
这是我收到的错误消息:
HttpError: https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json 返回“请求的 10 个维度;只允许 9 个。”>
有遇到同样错误的人能解决这个问题吗?
【问题讨论】:
-
根据 google API 参考文档,似乎并非所有维度都允许,仅允许某些组合。参考:developers.google.com/analytics/devguides/reporting/core/…
-
我认为错误与渠道分组无关。根据错误,您可以在请求中发送最多 9 个维度。因此,您可能希望从请求中删除
ga:month和ga:year,因为您可以从ga:date中提取这些值。
标签: python google-api google-analytics-api google-api-python-client