본문 바로가기
python-기타

Google Analytics Data API과 Python을 활용한 데이터 수집(Data collection using Google Analytics Data API and Python)

by 무적김두칠 2023. 5. 11.

 

https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries?hl=en#python 

developers.google.com
위 링크의 내용을 따라 진행하시면 되고 (영어로!)
Step 2 내용은 내려받은 json 파일에서 client_email에 해당하는 부분을 사용하시면 됩니다.

You can proceed by following the link above.
For Step 2, use the part corresponding to client_email in the downloaded json file.

 

13300685251740183869  |  Google Analytics Data API  |  Google Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 13300685251740183869 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 16756744891110588087 달리 명

developers.google.com

 

 

그리고 pip를 통해 라이브러리를 설치하고 밑에 코드를 실행시키면 
분명히 설치했음에도
 ModuleNotFoundError: No module named 'google.analytics'

과 같은 에러가 뜰텐데 

And if you install the library through pip and run the code below
even though it was installed
 ModuleNotFoundError: No module named 'google.analytics'

You will get an error like


https://github.com/googleapis/python-analytics-data#installation

 

GitHub - googleapis/python-analytics-data

Contribute to googleapis/python-analytics-data development by creating an account on GitHub.

github.com

위 깃헙 페이지의 최하단 부분을 보면 
운영체제에 맞게 가상환경을 설정후에 그 환경에서 라이브러리를 설치하셔야 됩니다.

If you look at the bottom of the Github page above,
After setting the virtual environment according to the operating system, you need to install the library in the environment.

 

1
2
3
4
pip install virtualenv
virtualenv ga4
ga4\Scripts\activate
ga4\Scripts\pip.exe install google-analytics-data
cs

저 같은 경우는 ga4라고 가상환경 이름을 짓고 하면 위와 같습니다.

In my case, if I name the virtual environment ga4, it looks like the above.

Before Activate
After Actvate

 

제가 원하는 Dimension과 Metric을 얻는 코드 샘플도 공유 드릴게요

I'll also share a code sample to get the dimensions and metrics I want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
import os
import pandas as pd
 
def fetch_ga4_data(property_id):
    credential_path = "credentials.json"
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'= credential_path
 
    client = BetaAnalyticsDataClient()
 
    dimensions = [
        Dimension(name="date"),
        Dimension(name="eventName"),
        Dimension(name="Country"),
        Dimension(name="region"),
        Dimension(name="city"),
        #Dimension(name="cityId"),
        Dimension(name="dayOfWeekName"),
        Dimension(name="hour"),
        Dimension(name="pageTitle"),
        Dimension(name="sessionDefaultChannelGroup"),
        #Dimension(name="deviceCategory")
 
 
    ]
    metrics = [
 
        Metric(name="eventCount"),
        Metric(name="userEngagementDuration"),
        Metric(name="activeUsers"),
        Metric(name="sessions"),
        Metric(name="engagedSessions")
        # Metric(name="newUsers"),
        #Metric(name="screenPageViews")
 
    ]
 
    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=dimensions,
        metrics=metrics,
        date_ranges=[DateRange(start_date="2020-01-01", end_date="today")],
    )
 
    response = client.run_report(request)
 
    rows = []
    for row in response.rows:
        dimension_values = [dimension_value.value for dimension_value in row.dimension_values]
        metric_values = [metric_value.value for metric_value in row.metric_values]
        rows.append(dimension_values + metric_values)
 
    columns = [dimension.name for dimension in dimensions] + [metric.name for metric in metrics]
    df = pd.DataFrame(rows, columns=columns)
 
    df.to_excel("ga4_data.xlsx", index=False)
 
fetch_ga4_data(property_id="your_id")
 
cs

'your - id' 에 해당하는 부분은 GA 홈에서 저기서 확인하시면 됩니다

You can check the part corresponding to 'your - id' there on the GA home.

이상으로 Google Analytics Data API과 Python을 활용한 데이터 수집 에 대한 글 마칩니다. 
더 많은 Dimension 과 Matircs 들에 대해서 궁금하시다면  하당 링크에서 확인 가능합니다.

This concludes the article on data collection using Google Analytics Data API and Python.
If you are curious about more Dimensions and Matircs, you can check them at the link below.
https://ga-dev-tools.google/ga4/dimensions-metrics-explorer/

 

GA4 Dimensions & Metrics Explorer

 

ga-dev-tools.google

 

반응형

'python-기타' 카테고리의 다른 글

split(), split(" ")의 차이점  (0) 2022.10.26
Python isnumeric()에 관한 건  (0) 2022.10.21
print vs pprint  (0) 2021.12.30
reverse 와 reversed 차이  (0) 2021.12.28

댓글