我试图调用谷歌分析核心报告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:batgetGet?val = json返回“请求10个维度;仅允许9个维度。”>
有没有人得到同样的错误能够解决这个问题?
要求10个维度;只允许9个。
意味着您正在发送10个维度,您一次只允许向api呼叫发送9个维度。删除下面的一个尺寸。我可以建议删除{'name':'ga:year'}和{'name':'ga:month'}你已经要求约会,你真的不需要那些。
'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'}],