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
|
import csv, argparse
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Dimension, Filter, FilterExpression, Metric, RunReportRequest, OrderBy
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help='output file name')
args = parser.parse_args()
KEYFILE = '../client_secret.json'
OUTFILE = args.output
def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
client = BetaAnalyticsDataClient().from_service_account_json(KEYFILE)
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="date")],
dimension_filter = FilterExpression(filter=Filter(field_name="date", string_filter=Filter.StringFilter(match_type="EXACT", value="2022-04-01"))),
metrics=[Metric(name="eventCount")],
date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")],
order_bys=[OrderBy(dimension=OrderBy.DimensionOrderBy(dimension_name="date"))]
)
response = client.run_report(request)
data=[]
for row in response.rows:
raw=[]
for dimension in row.dimension_values:
raw.append(dimension.value)
for metric in row.metric_values:
raw.append(metric.value)
data.append(raw)
with open(OUTFILE, 'w') as f:
write = csv.writer(f)
write.writerows(data)
if __name__ == '__main__':
sample_run_report()
|