Python Google Analytics API获取特定于性别和年龄的Url
当我使用下面的代码时 我根据日期范围和我的特定URL接收访问计数。但我想改变这一点,在特定页面上获取用户的年龄和性别。我该怎么办 所以我想要这样的东西 日期=2020年10月10日-2020年10月11日 url=/mypage 性别=%55女性-%45男性 年龄=%55 18-24/%45 24-48/%5Python Google Analytics API获取特定于性别和年龄的Url,python,Python,当我使用下面的代码时 我根据日期范围和我的特定URL接收访问计数。但我想改变这一点,在特定页面上获取用户的年龄和性别。我该怎么办 所以我想要这样的东西 日期=2020年10月10日-2020年10月11日 url=/mypage 性别=%55女性-%45男性 年龄=%55 18-24/%45 24-48/%5 from apiclient.discovery import build from oauth2client.service_account import ServiceAccountC
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'keyfilehere'
VIEW_ID = 'myviewidhere'
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': '2020-10-01', 'endDate': '2020-10-28'}],
'metrics': [{"expression": "ga:pageviews"}],
'dimensions': [{'name': 'ga:pagePath'}],
"dimensionFilterClauses": [
{"filters": [{"operator": "EXACT", "dimensionName": "ga:pagePath", "expressions": ["/my-page-url"]}]}],
}]
}
).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()```