<p>您应该考虑使用服务帐户。服务帐户与虚拟用户类似,您可以通过获取服务帐户电子邮件地址并将其添加为您希望访问的帐户上的用户,对服务帐户访问您的Google analytics帐户进行预授权。通过这样做,代码将不需要像您当前看到的那样由用户授权</p>
<p>服务帐户应仅用于开发人员拥有的帐户,而不应用于访问其他用户的帐户,因为您应该使用Oauth2</p>
<p>官方教程可以在这里找到<a href="https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py" rel="nofollow noreferrer">Hello Analytics Reporting API v4; Python quickstart for service accounts</a></p>
<pre><code>"""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 = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
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,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
).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()
</code></pre>
<p>您需要在Google开发者控制台上创建服务帐户凭据。您现在使用的凭据将不起作用。这是一段关于<a href="https://youtu.be/asrCdWFrF0A" rel="nofollow noreferrer">How to create Google Oauth2 Service account credentials.</a>的视频</p>
<p>记住在库下启用Google analytics Reporting api</p>