【问题标题】:google analytics api with python谷歌分析 api 与 python
【发布时间】:2016-05-11 17:54:37
【问题描述】:

http://www.marinamele.com/use-google-analytics-api-with-python

您好,我按照本教程尝试使用 python 访问谷歌分析 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代码后,它给了我一个新的浏览器窗口,并询问我访问谷歌分析数据的权限,点击允许后,它显示:没有收到数据。

我做错了什么?

谢谢

【问题讨论】:

  • 您是否创建了 ID ????并在你的代码中输入?
  • 不知道该教程,但如果您想通过脚本访问 API(无需浏览器身份验证),您可以使用 Google 自己的 Python 示例:developers.google.com/analytics/devguides/reporting/core/v3/…
  • 非常感谢大家,我找到了经理为我的帐户编辑错误权限的原因。

标签: python google-analytics google-api-python-client


【解决方案1】:

其实你没有做错什么:

新的浏览器窗口仅用于凭据检查。

您刚刚初始化了一个对象,但没有调用任何报告。

你需要这样的东西:

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"}] 
     }
    ]
    }]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多