Python-问题-使用循环每天获取

Python-问题-使用循环每天获取,python,while-loop,google-api,google-analytics-api,google-api-python-client,Python,While Loop,Google Api,Google Analytics Api,Google Api Python Client,我正在尝试制作一个可以绕过api限制的GoogleAPI下载程序。 不幸的是,我所做的不起作用。由于我没有引入循环,不幸的是,在下载历史数据时,手工更改日期非常容易。对于新数据,skypt每天生成数据没有问题。 下面是我每天尝试从特定范围下载数据的代码 问题发生在代码的这一部分 def get_top_keywords(service, profile_id): for day_number in range(total_days): return service.data().ga()

我正在尝试制作一个可以绕过api限制的GoogleAPI下载程序。 不幸的是,我所做的不起作用。由于我没有引入循环,不幸的是,在下载历史数据时,手工更改日期非常容易。对于新数据,skypt每天生成数据没有问题。 下面是我每天尝试从特定范围下载数据的代码

问题发生在代码的这一部分

def get_top_keywords(service, profile_id):

 for day_number in range(total_days):
  return service.data().ga().get(
        ids='ga:' + profile_id,
        start_date='1daysAgo',
        end_date=(start_date + dt.timedelta(days = day_number)).date(),
        metrics='ga:sessions, ga:newUsers, ga:users, ga:organicSearches, ga:pageviews, ga:bounceRate',
        dimensions='ga:date, ga:source, ga:medium',
        max_results='10000').execute()
在整个代码下面

import argparse
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import csv
from __future__ import print_function

from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError
import datetime as dt

start_date = dt.datetime(2019, 01,1)
end_date = dt.datetime(2019, 01,5)

total_days = (end_date - start_date).days + 1


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'analytics', 'v3', __doc__, __file__,
      scope='https://www.googleapis.com/auth/analytics.readonly')

  # Try to make a request to the API. Print the results or handle errors.
  try:
    first_profile_id = '11111111111' # Hard Code View Profile ID Here
    if not first_profile_id:
      print('Could not find a valid profile for this user.')
    else:
      results = get_top_keywords(service, first_profile_id)
      print_results(results)

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

  except HttpError as 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):
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    firstAccountId = accounts.get('items')[0].get('id')
    webproperties = service.management().webproperties().list(
        accountId=firstAccountId).execute()

    if webproperties.get('items'):
      firstWebpropertyId = webproperties.get('items')[0].get('id')
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        return profiles.get('items')[0].get('id')

  return None


def get_top_keywords(service, profile_id):

 for day_number in range(total_days):
  return service.data().ga().get(
        ids='ga:' + profile_id,
        start_date='1daysAgo',
        end_date=(start_date + dt.timedelta(days = day_number)).date(),
        metrics='ga:sessions, ga:newUsers, ga:users, ga:organicSearches, ga:pageviews, ga:bounceRate',
        dimensions='ga:date, ga:source, ga:medium',
        max_results='10000').execute()


def print_results(results):

  print()
  print('Profile Name: %s' % results.get('profileInfo').get('profileName'))
  print()

  # Open a file.
  filepath = '/temp/'    #change this to your actual file path
  filename = 'temp.csv'         #change this to your actual file name
  f = open(filepath + filename, 'wt')

  # Wrap file with a csv.writer
  writer = csv.writer(f, lineterminator='\n')

  # Write header.
  header = [h['name'][3:] for h in results.get('columnHeaders')] #this takes the column headers and gets rid of ga: prefix
  writer.writerow(header)
  print(''.join('%30s' %h for h in header))

  # Write data table.
  if results.get('rows', []):
    for row in results.get('rows'):
      writer.writerow(row)
      print(''.join('%30s' %r for r in row))

    print('\n')
    print ('Success Data Written to CSV File')
    print ('filepath = ' + filepath)
    print ('filename = '+ filename)

  else:
    print ('No Rows Found')

  # Close the file.
  f.close()


if __name__ == '__main__':
  main(sys.argv)
我应该改进什么以使日期自动到达循环的末尾?

为什么循环不起作用,我只是从python开始,但我正在尝试

是的,我添加了一个循环,我只是做了一些错误的事情,因为当我测试循环本身时,它起作用了,但是当我将它应用到连接到api的代码时,它就不再起作用了


 for day_number in range(total_days):
  return service.data().ga().get(
        ids='ga:' + profile_id,
        start_date='1daysAgo',
        end_date=(start_date + dt.timedelta(days = day_number)).date(),
        metrics='ga:sessions, ga:newUsers, ga:users, ga:organicSearches, ga:pageviews, ga:bounceRate',
        dimensions='ga:date, ga:source, ga:medium',
        max_results='10000').execute()

您现在的代码有什么错误/问题?你试过添加一个循环吗?