簡體   English   中英

使用Python連接到Google Analytics(分析)API

[英]Connecting to Google Analytics API using Python

我嘗試按照本教程連接到Google Analytics(分析)API。 我已按照指示逐步進行。 我的計算機上安裝了Python 2.7。 我已經安裝了Google客戶端庫。 當我運行程序時,在終端中出現以下錯誤:

Traceback (most recent call last):
  File "HelloAnalytics.py", line 6, in <module>
    from oauth2client.client import SignedJwtAssertionCredential
ImportError: cannot import name SignedJwtAssertionCredentials

它引用的第6行是:

from oauth2client.client import SignedJwtAssertionCredentials

我完全迷路了。 我查看了在這里這里這里有相同錯誤的其他人,但是解決方案不起作用。 我有一些編程知識,但與你們中的許多人相比,我是新手。

完整代碼在這里:

"""A simple example of how to access the Google Analytics API."""

import argparse

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

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.
  """

  f = open(key_file_location, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(service_account_email, key,
    scope=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()

任何幫助或方向將不勝感激。

源存儲庫最近已更新,並且此后還更新了《 Hello Analytics指南》以使用新代碼:

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

...
credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

其中service_account_email是您從開發人員控制台獲得的服務帳戶的電子郵件地址, key_file_locaiton/the/path/to/key.p12scopes是您需要授予服務帳戶的作用域

請記住,將服務帳戶電子郵件地址添加為您希望其有權訪問的Google Analytics(分析)數據視圖(配置文件)的授權用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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