[英]google analytics api with python
http://www.marinamele.com/use-google-analytics-api-with-python
嗨,我按照本教程尝试使用python访问google analytics api。
代码是这样的:
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse
CLIENT_SECRETS = 'client_secrets.json'
# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
message='%s is missing' % CLIENT_SECRETS
)
# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'
def prepare_credentials():
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
# Retrieve existing credendials
storage = Storage(TOKEN_FILE_NAME)
credentials = storage.get()
# If no credentials exist, we create new ones
if credentials is None or credentials.invalid:
credentials = tools.run_flow(FLOW, storage, flags)
return credentials
def initialize_service():
# Creates an http object and authorize it using
# the function prepare_creadentials()
http = httplib2.Http()
credentials = prepare_credentials()
http = credentials.authorize(http)
# Build the Analytics Service Object with the authorized http object
return build('analytics', 'v3', http=http)
if __name__ == '__main__':
service = initialize_service()
运行python代码后,它给了我一个新的浏览器窗口,并询问我访问Google Analytics(分析)数据的权限,单击“允许”后,它显示:没有收到数据。
我做错了什么?
谢谢
实际上,您在这里没有做错任何事情:
新的浏览器窗口仅用于凭据检查。
您只是初始化了一个对象,但没有调用任何报告。
您将需要以下内容:
service.reports().batchGet(body={'reportRequests' : config['reportRequests']}).execute()
从分析中获取数据。 在此示例中:
config['reportRequests'] =
"reportRequests": [
{
"viewId": "SOME FANCY VIEW ID",
"dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
"metrics": [{"expression": "ga:pageviews"}, {"expression":"ga:sessions"}],
"dimensions": [{"name": "ga:adContent"},{"name":"ga:landingPagePath"}],
"dimensionFilterClauses":
[
{
"filters": [{"dimensionName": "ga:source", "expressions":"SOME UTM-SOURCE"}]
}
]
}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.