Python with Google Analytics 从 Googles 脚本中查询特定的 Google 帐户
Python with Google Analytics Querying a specific Google Account from Googles scripts
我是 Python 的新手,从 Google Analytics API 帮助中获得了以下脚本。我已经让它工作并提取数据,但是,它指定获取第一个 google 帐户,我有多个 GA 帐户并且希望只指定一个。有什么帮助会很好吗?
谢谢
克雷格
"""A simple example of how to access the Google Analytics API."""
import argparse
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, key_file_location,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account p12 key file.
service_account_email: The service account email address.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email, key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
print 'Total Sessions: %s' % results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']
# Use the developer console and replace the values with your
# service account email and relative location of your key file.
service_account_email = '<Replace with your service account email address.>'
key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'
# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, key_file_location,
service_account_email)
profile = get_first_profile_id(service)
print_results(get_results(service, profile))
if __name__ == '__main__':
main()
注释掉(或删除)以下行:
profile = get_first_profile_id(service)
在下一行中输入您要手动查询的配置文件的 ID 作为第二个参数
print_results(get_results(service, '123456789'))
要获取配置文件 ID,您可以访问 query explorer,这是一个不错的 google 工具,它允许对您经过身份验证的帐户进行临时查询(即您需要使用 Google 有权访问分析的帐户)。您可以从 "ids" 字段中获取配置文件 ID:
或者访问您的分析帐户,并在报告中查看 url。看起来像
https://analytics.google.com/analytics/web/?authuser=0#report/defaultid/a1111110w65439246p123456789/
配置文件 ID 在 url 的末尾(在 "p" 字符之后)。
查看 this post 它有适应 Google Analytics Python 示例代码的代码,您可以添加多个配置文件 ID。
profile_ids = profile_ids = {'My Profile 1': '1234567',
'My Profile 2': '1234568',
'My Profile 3': '1234569',
'My Profile 4': '1234561'}
# Uncomment this line & replace with 'profile name': 'id' to query a single profile
# Delete or comment out this line to loop over multiple profiles.
## profile_ids = {'ryanpraski': '1234567'}
-瑞安
我是 Python 的新手,从 Google Analytics API 帮助中获得了以下脚本。我已经让它工作并提取数据,但是,它指定获取第一个 google 帐户,我有多个 GA 帐户并且希望只指定一个。有什么帮助会很好吗?
谢谢
克雷格
"""A simple example of how to access the Google Analytics API."""
import argparse
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, key_file_location,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account p12 key file.
service_account_email: The service account email address.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email, key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
print 'Total Sessions: %s' % results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']
# Use the developer console and replace the values with your
# service account email and relative location of your key file.
service_account_email = '<Replace with your service account email address.>'
key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'
# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, key_file_location,
service_account_email)
profile = get_first_profile_id(service)
print_results(get_results(service, profile))
if __name__ == '__main__':
main()
注释掉(或删除)以下行:
profile = get_first_profile_id(service)
在下一行中输入您要手动查询的配置文件的 ID 作为第二个参数
print_results(get_results(service, '123456789'))
要获取配置文件 ID,您可以访问 query explorer,这是一个不错的 google 工具,它允许对您经过身份验证的帐户进行临时查询(即您需要使用 Google 有权访问分析的帐户)。您可以从 "ids" 字段中获取配置文件 ID:
或者访问您的分析帐户,并在报告中查看 url。看起来像
https://analytics.google.com/analytics/web/?authuser=0#report/defaultid/a1111110w65439246p123456789/
配置文件 ID 在 url 的末尾(在 "p" 字符之后)。
查看 this post 它有适应 Google Analytics Python 示例代码的代码,您可以添加多个配置文件 ID。
profile_ids = profile_ids = {'My Profile 1': '1234567',
'My Profile 2': '1234568',
'My Profile 3': '1234569',
'My Profile 4': '1234561'}
# Uncomment this line & replace with 'profile name': 'id' to query a single profile
# Delete or comment out this line to loop over multiple profiles.
## profile_ids = {'ryanpraski': '1234567'}
-瑞安