python - 谷歌分析 API 问题

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

所以我目前正在开展一个小组项目,我们正在使用 Google Analytics 提取数据,并且需要将 API 与 Google Analytics 合并以用于我们正在创建的数据库。我们遇到了无法让 API 正常工作的问题。我们需要一个 View ID,但对于我们的生活来说,我们无法弄清楚如何仅使用 Web Property 创建帐户,因为它根本没有为我们提供创建 Web Property 的选项。每当我们尝试创建一个新帐户时,它都会将我们置于测试版的应用程序和网络属性分析中,它不会为您提供 View 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")

最佳答案

Google Analytics Data API v1 可以为 GA4 Properties 创建报告。查看developer's site . Google Analytics Reporting API v4 可以为 Universal Analytics (GA3) Views (reference) 创建报告。您编写的代码使用的是 Google Analytics Reporting v4。

所以你有两个选择:

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

关于python - 谷歌分析 API 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66377137/

相关文章:

python - 事件处理 : Matplotlib's Figure() and pyplot's figure()

python - 如何在保持 y 值范围的同时结合两个 Seaborn 线图?

javascript - OPTIONS 请求应该返回 429 吗?

api - WSO2 API 管理器支持 API 联合吗?

android - Google Analytics 不跟踪交易数量

python - 故障排除 "descriptor ' 日期'需要 'datetime.datetime' 对象,但收到 'int'“

Python KeyError : <peewee. IntegerField 对象在 ... > 使用 peewee insert_many()

image - 如何在我的 flutter 应用程序中从 bing web search apiv7 获取图像

url - Google Analytics 不显示广告系列的 url 参数

php - 如何在 php web 服务中包含谷歌分析