将pageToken与Google Analytics Reporting API v4和Python结合使用

时间:2019-01-24 16:19:53

标签: python api google-analytics

我遵循了有关如何使用GA Reporting API使用Python从Google Analytics(分析)下载数据的教程。尽管达到了行数限制,但我仍然能够查询所需的数据。 我在文档中看到有一个pageToken可以避免该问题。我已将此字段添加到我的请求中(如文档中所述),但无法使其正常工作。

sample_request = {
      'viewId': '18149780',
      'dateRanges': {
          'startDate': datetime.strftime(datetime.now() - timedelta(days = 30),'%Y-%m-%d'),
          'endDate': datetime.strftime(datetime.now(),'%Y-%m-%d')
      },
      'dimensions': [
          {'name': 'ga:date'},
          {'name': 'ga:dimension7'},
          {'name': 'ga:dimension6'},
          {'name': 'ga:dimension9'}
      ],
      'metrics': [
          {'expression': 'ga:users'},
          {'expression': 'ga:totalevents'}
      ],
      "pageSize": 100000,
      'pageToken': 'abc'
    }

response = api_client.reports().batchGet(
      body={
        'reportRequests': sample_request
      }).execute()

2 个答案:

答案 0 :(得分:1)

您将达到限制,但是参数 nextPageToken 将允许您分页浏览多行。例如:

def processReport (self, aDimensions):
    """Get a full report, returning the rows"""

    # Get the first set
    oReport   = self.getReport(aDimensions)
    oResponse = self.getResponse(oReport, True)
    aRows     = oResponse.get('rows')

    # Add any additional sets
    while oResponse.get('nextPageToken') != None:
        oResponse = self.getReport(aDimensions, oResponse.get('nextPageToken'))
        oResponse = self.getResponse(oResponse, False)
        aRows.extend(oResponse.get('rows'))

    return aRows

您可以在此处查看完整的程序: https://github.com/aiqui/ga-download

答案 1 :(得分:0)

我这样解决了

def handle_report(analytics,pagetoken,rows):  

    response = get_report(analytics, pagetoken)

    columnHeader = response.get("reports")[0].get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    pagetoken = response.get("reports")[0].get('nextPageToken', None)
    rowsNew = response.get("reports")[0].get('data', {}).get('rows', [])
    rows = rows + rowsNew
    print("len(rows): " + str(len(rows)))

    if pagetoken != None:
        return handle_report(analytics,pagetoken,rows)
    else:
        return rows

def main():    
    analytics = initialize_analyticsreporting()

    global dfanalytics
    dfanalytics = []

    rows = []
    rows = handle_report(analytics,'0',rows)

    dfanalytics = pd.DataFrame(list(rows))