我正在将Google Analytics Reporting API v4与Python3配合使用,从老板共享给我的Google Analytics(分析)仪表板上提取数据。我正在使用私钥和服务帐户。
我想做的:使用由Google Analytics(分析)信息中心的管理员创建的自定义/高级细分。该管理员已将“高级细分”更改为协作细分,因此我可以访问自己帐户中的细分。
我能够提取预定义段(如(gaid ::-3))的数据。但这只是测试用例。当我尝试使用自定义/高级细分而不是预定义的Google细分时,就会出现问题。
代码:
"""Hello Analytics Reporting API V4."""
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'fakefilelocation.json'
VIEW_ID = '111111'
def initialize_analyticsreporting():
"""Initializes an Analytics Reporting API V4 service object.
Returns:
An authorized Analytics Reporting API V4 service object.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
{
"viewId":VIEW_ID,
"dimensions":[{"name": "ga:segment"},{"name":"ga:dimension4"}],
"dateRanges":[{"startDate":"2017-10-10","endDate":"2017-10-10"}],
"metrics":[{"expression":"ga:sessions","alias":"sessions"}],
"segments":[{"segmentId": "gaid::1111111111111"}]
}]
}
).execute()
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response.
Args:
response: An Analytics Reporting API V4 response.
"""
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
for row in report.get('data', {}).get('rows', []):
dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])
for header, dimension in zip(dimensionHeaders, dimensions):
print(header + ': ' + dimension)
for i, values in enumerate(dateRangeValues):
print('Date range: ' + str(i))
for metricHeader, value in zip(metricHeaders, values.get('values')):
print(metricHeader.get('name') + ': ' + value)
def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)
if __name__ == '__main__':
main()
但是这会导致错误:
---------------------------------------------------------------------------
HttpError Traceback (most recent call last)
<ipython-input-10-f6bd25c075a6> in <module>()
76
77 if __name__ == '__main__':
---> 78 main()
<ipython-input-10-f6bd25c075a6> in main()
72 def main():
73 analytics = initialize_analyticsreporting()
---> 74 response = get_report(analytics)
75 print_response(response)
76
<ipython-input-10-f6bd25c075a6> in get_report(analytics)
41 "dateRanges":[{"startDate":"2017-10-10","endDate":"2017-10-10"}],
42 "metrics":[{"expression":"ga:sessions","alias":"sessions"}],
---> 43 "segments":[{"segmentId": "gaid::1111111111111"}]
44 }]
45 }
C:\ProgramData\Anaconda3\lib\site-packages\oauth2client\_helpers.py in positional_wrapper(*args, **kwargs)
131 elif positional_parameters_enforcement == POSITIONAL_WARNING:
132 logger.warning(message)
--> 133 return wrapped(*args, **kwargs)
134 return positional_wrapper
135
C:\ProgramData\Anaconda3\lib\site-packages\googleapiclient\http.py in execute(self, http, num_retries)
840 callback(resp)
841 if resp.status >= 300:
--> 842 raise HttpError(resp, content, uri=self.uri)
843 return self.postproc(resp, content)
844
HttpError: <HttpError 403 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "User does not have sufficient permissions for this advanced segment.">
我很确定这不是错误的段ID的结果,因为我尝试了一个假的(“ 1111111111111”),它给了我一个不同的错误。
总结我想使用Google Analytics(分析)Reporting API v4来提取和打印由Admin用户(而非我)拥有的自定义/高级细分排序的数据。这样,如果管理员更改了“自定义细分”上的设置,这些更改自然就会流到我的数据提取中。
[如果您将细分的可见性设置更改为“协作者,并且我可以在此视图中应用/编辑细分”,则服务帐户应该可以看到它。
[在Google Analytics(分析)网络界面中,编辑细分(管理>视图>细分>选择适当的细分)。在右上角显示“段已显示并在当前视图中共享”的位置,单击“更改”并应用新设置。