簡體   English   中英

帶有python的google analytics api

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM