首页 > 解决方案 > Python,Pandas 数据框中的 Google 服务对象?

问题描述

我们有一家在线公司。该网站包含许多功能,我们想分析哪些客户访问了哪些网站以及访问了多少次。

问题:

我正在尝试编写一个程序,该程序应该使用某些 Google Analytics 数据来创建一个 HTML 表(使用 pandas),可以随时使用最新的 Google Analytics 数据查看该表。

我做了什么:

我已经设法通过身份验证并拥有所有权限(我相信是因为我还没有收到权限错误消息)并返回一个我不知道如何使用/打开的服务对象?

#!/usr/bin/env python3

"""Script that does the following:
 1) Initialise a Google Analytics Reporting API service object
"""
import os
import argparse
from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
import yaml
import pandas as pd

scopes = ['https://www.googleapis.com/auth/analytics.readonly']
# Path to client_secrets.json file.
client_secrets_path = 'credentials/client_secret_xx.apps.googleusercontent.com.json'


def initialise_analyticsreporting():
    """Initializes the analyticsreporting service object.

  Returns:
    an authorized analyticsreporting service object.
  """
    # Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        "credentials/client_secret_xx.apps.googleusercontent.com.json",
        scope='https://www.googleapis.com/auth/analytics.readonly',
        message=tools.message_if_missing(client_secrets_path))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage('credentials/analyticsreporting.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Build the service object.
    analytics = build('analyticsreporting', 'v4', http=http)

    return analytics

这将返回分析,如下所示<googleapiclient.discovery.Resource object at 0x00000XOXOXOXOX>

归根结底,我只想将 Google Analytics 数据放在 pandas 数据框中,以便我可以操作和使用它。我不是谷歌分析专家。这对我们的业务至关重要,我们将不胜感激。我真的很摸不着头脑。

预期输出(作为我想要实现的目标的指导,我对 Pandas 相当熟练。问题是从 GA 获取数据):

user_id  site               visits
123      abc.com/something  12
234      abc.com/smthngelse 7

谢谢,很高兴回答问题

标签: pythonpandasgoogle-analytics

解决方案


您的analytics对象只是一个服务对象 - 您可以使用它来访问返回数据的方法,但它本身并不包含 Google Analytics 数据。当您使用的是核心报告 API 的第 4 版时,您可以从文档中查看此示例:

def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}]
        }]
      }
  ).execute()

更改指标并根据自己的喜好添加维度(但并非每个组合都有效或有意义),输入您的视图 ID,您应该一切顺利。


推荐阅读