from cred import client_cred
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
import pandas as pd
CUSTOMER_ID = pass
# CUSTOMER_ID = pass
def get_value(response):
new_list = []
stream = response
i = 1
col_names = ["keyword_text","match_type_name","ad_group_name","campaign_name",
"campaign_id","impressions","clicks","cost_micros","average_cpc","average_cpm","cost_per_all_conversions",
"cost_per_conversion"]
for batch in stream:
for row in batch.results:
campaign = row.campaign
ad_group = row.ad_group
criterion = row.ad_group_criterion
metrics = row.metrics
fetch_list = [(criterion.keyword.text),(criterion.keyword.match_type.name),(ad_group.name),(campaign.name),
(campaign.id),(metrics.impressions),(metrics.clicks),(metrics.cost_micros),(metrics.average_cpc),(metrics.average_cpm),
(metrics.cost_per_all_conversions),(metrics.cost_per_conversion)]
new_list.append(fetch_list)
new_df = pd.DataFrame(new_list, columns=col_names)
new_df.to_csv("batch_{}.csv".format(i))
i+=1
def run_query(client,customer_id):
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT campaign.id,campaign.name,ad_group.id,ad_group.name, ad_group_criterion.criterion_id, ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type,
metrics.impressions,
metrics.clicks,
metrics.cost_micros,
metrics.average_cpc,
metrics.average_cpm,
metrics.cost_per_all_conversions,
metrics.cost_per_conversion
FROM keyword_view
WHERE segments.date BETWEEN "2022-03-01" AND "2022-03-31"
AND campaign.advertising_channel_type = 'SEARCH'
AND ad_group.status = 'ENABLED'
AND ad_group_criterion.status IN ('ENABLED', 'PAUSED')
ORDER BY metrics.impressions DESC
"""
cols = query.split("FROM")[0].replace("SELECT ","").split(",")
cols = [x.replace("\n","").replace(" ","").replace("\t","") for x in cols]
search_request = client.get_type("SearchGoogleAdsStreamRequest")
search_request.customer_id = customer_id
search_request.query = query
stream = ga_service.search_stream(search_request)
return stream
if __name__=="__main__":
client = client_cred()
customer_id = CUSTOMER_ID
stream = run_query(client=client,customer_id=customer_id)
print("Fetched Successfully")
get_value(stream)