谷歌分析 API 问题

时间:2021-02-25 22:05:03

标签: python api google-analytics jupyter-notebook google-analytics-api

所以我目前正在开展一个小组项目,我们正在使用 Google Analytics 来提取数据,并且需要将 API 与 Google Analytics 合并以用于我们正在创建的数据库。我们遇到了无法让 API 正常工作的问题。我们需要一个视图 ID,但在我们的生活中,我们无法弄清楚如何仅使用网络资产创建帐户,因为它根本没有为我们提供创建网络资产的选项。每当我们尝试创建新帐户时,它都会将我们置于应用和网站属性分析的测试版中,该版本不会为您提供查看 ID。

我们也尝试创建一个新的 Google 帐户,但无济于事。

下面附上我们的代码,如果有人能帮助我们绕过这种情况,或者告诉我们我们需要做什么才能创建一个 Web Property,我们将不胜感激!

我们使用 Python 编写代码并使用 JUPYTER

#Load Libraries
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
import httplib2
import pandas as pd

#Create service credentials
#Rename your JSON key to client_secrets.json and save it to your working folder
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', 
['https://www.googleapis.com/auth/analytics.readonly'])

#Create a service object
http = credentials.authorize(httplib2.Http())
service = build('analytics', 'v4', http=http, discoveryServiceUrl= 
('https://analyticsreporting.googleapis.com/$discovery/rest'))
response = service.reports().batchGet(
body={
    'reportRequests': [
        {
            'viewId': '261713611', #Add View ID from GA
            'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
            'metrics': [{'expression': 'ga:sessions'}], 
            'dimensions': [{"name": "ga:pagePath"}], #Get Pages
            "filtersExpression":"ga:pagePath=~products;ga:pagePath!@/translate", #Filter by condition "containing products"
            'orderBys': [{"fieldName": "ga:sessions", "sortOrder": "DESCENDING"}], 
            'pageSize': 100
         }]
 }
).execute()

#create two empty lists that will hold our dimentions and sessions data
dim = []
val = []

#Extract Data
for report in response.get('reports', []):

columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
rows = report.get('data', {}).get('rows', [])

for row in rows:

    dimensions = row.get('dimensions', [])
    dateRangeValues = row.get('metrics', [])

    for header, dimension in zip(dimensionHeaders, dimensions):
        dim.append(dimension)

    for i, values in enumerate(dateRangeValues):
        for metricHeader, value in zip(metricHeaders, values.get('values')):
            val.append(int(value))

#Sort Data
val.reverse()
dim.reverse()

df = pd.DataFrame() 
df["Sessions"]=val
df["pagePath"]=dim
df=df[["pagePath","Sessions"]]
df

#Export to CSV
df.to_csv("page_by_session.csv")

1 个答案:

答案 0 :(得分:0)

Google Analytics Data API v1 可以为 GA4 媒体资源创建报告。请参阅developer's site。 Google Analytics Reporting API v4 可以为 Universal Analytics (GA3) 视图 (reference) 创建报告。您编写的代码使用的是 Google Analytics Reporting v4。

所以你有两个选择:

  1. 向数据 API v1 发送请求。使用 GA4 媒体资源标记您的网站。
  2. 向 Reporting API v4 发送请求。使用 GA3(通用分析)标记您的网站。此 guide 展示了如何创建 Universal Analytics 媒体资源。今天的默认新资产是 GA3 资产。