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

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

问题描述:

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

I have followed a tutorial on how to download data from Google Analytics with Python using GA Reporting API. I was able to query the data I wanted, although reaching the rows limit. I saw in the documentation that there is a pageToken to avoid the issue. I have added this field to my request (as describe in the documentation), but I am not able to make it work.

sample_request = {
      'viewId': '12345678',
      '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()

您将达到限制,但参数 nextPageToken 将允许您翻阅多行.例如:

You will hit the limit, but the parameter nextPageToken will allow you to page through multiple rows. For example:

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

You can see the complete program here: https://github.com/aiqui/ga-download