Python中的谷歌分析API

Python中的谷歌分析API,python,google-analytics,Python,Google Analytics,我正在尝试使用Python查询Google Analytics API。我遵循了文档中的示例。(我已经做了非常小的更改来帮助我调试我遇到的问题)。我一直得到一个“非类型”对象没有属性“\uuu getitem\uuu”,我似乎无法解释。我只是遵循谷歌提供的文档中的例子,该文档试图获取2012年3月3日的ga:visits数据 我正在运行的代码是: #!/usr/bin/python # -*- coding: utf-8 -*- import sys # import the Auth He

我正在尝试使用Python查询Google Analytics API。我遵循了文档中的示例。(我已经做了非常小的更改来帮助我调试我遇到的问题)。我一直得到一个“非类型”对象没有属性“\uuu getitem\uuu”,我似乎无法解释。我只是遵循谷歌提供的文档中的例子,该文档试图获取2012年3月3日的ga:visits数据

我正在运行的代码是:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# import the Auth Helper class
import hello_analytics_api_v3_auth

from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError

def main(argv):
  # Step 1. Get an analytics service object.
  print "I got here twice"
  service = hello_analytics_api_v3_auth.initialize_service()

  try:
    # Step 2. Get the user's first profile ID.
    profile_id = get_first_profile_id(service)
    print profile_id

    if profile_id:
      # Step 3. Query the Core Reporting API.
      results = get_results(service, profile_id)
      print "I got the results"

      # Step 4. Output the results.
      print_results(results)
      print "I printed the results"

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)

  except HttpError, error:
    # Handle API errors.
    print ('Arg, there was an API error : %s : %s' %
           (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run '
           'the application to re-authorize')

def get_first_profile_id(service):
  # Get a list of all Google Analytics accounts for this user
  print "I am trying to get first profile ID"
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account
    firstAccountId = accounts.get('items')[0].get('id')

    # Get a list of all the Web Properties for the first account
    webproperties = service.management().webproperties().list(accountId=firstAccountId).execute()

    if webproperties.get('items'):
      # Get the first Web Property ID
      firstWebpropertyId = webproperties.get('items')[0].get('id')

      # Get a list of all Profiles for the first Web Property of the first Account
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        # return the first 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
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2012-03-03',
      ##The start date dates range is hard coded here
      ##We have to change this so it becomes an input parameter
      end_date='2012-03-03',
      ##The end date is also hard coded in
      ##Change this to be an input parameter
      ##If you run out of ideas, read the start date off a txt file
      ##And then have the user change the text file before running
      ##the program
      metrics='ga:visits').execute()

def print_results(results):
  # Print data nicely for the user.
  print results
  if results:
    print 'First Profile: %s' % results.get('profileInfo').get('profileName')
    print 'Total Visits: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'

##if __name__ == '__main__':
main(sys.argv)
返回以下结果:

I got here twice
I am trying to get first profile ID
REDACT PROFILE ID
I got the results
{u'kind': u'analytics#gaData', u'containsSampledData': False}, u'itemsPerPage': 1000, u'totalsForAllResults': {u'ga:visits': u'0'}, u'columnHeaders': [{u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'ga:visits'}], u'query': {u'max-results': 1000, u'start-date': u'2012-03-03', u'start-index': 1, u'ids': u'ga:REDACTED', u'metrics': [u'ga:visits'], u'end-date': u'2012-03-03'}, u'totalResults': 0, u'id': u'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:4159539&metrics=ga:visits&start-date=2012-03-03&end-date=2012-03-03&start-index=1&max-results=1000', u'selfLink': u'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:4159539&metrics=ga:visits&start-date=2012-03-03&end-date=2012-03-03&start-index=1&max-results=1000'}
First Profile: H - REDACTED
There was an error in constructing your query : 'NoneType' object has no attribute '__getitem__'
有人能帮我们解释出什么地方出了问题,并告诉我们需要解决什么吗?:)


谢谢

在调用get函数之前,请确保对象不是空的。也许吧

service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

正在返回None和
配置文件。get('items')
失败。

对您来说太晚了,但可能有人会遇到类似的问题

是的,第一点错误是因为

      `service.management().profiles().list(
      accountId=firstAccountId,
      webPropertyId=firstWebpropertyId).execute()`

一个也没有。但易读的答案是,您在给定日期没有任何会话。这是在我的例子中,因为我想从2012年开始获取数据,API在结果中没有返回
('rows')

在我的例子中,只是在提到的日期之间我没有会话。因此返回了相同的“非类型”对象

是的,我也遇到了同样的问题。默认的日期范围是“最后七天”,因为没有会话,所以我收到了一个错误。但是,一旦我增加了日期范围,我就得到了所需的输出

什么类型是
结果