将 Google-Ads API GoogleAdsRow 转换为 ,CSV?

Convert Google-Ads API GoogleAdsRow to ,CSV?

Google Ads API,其新版本的 Google Adwords API returns 数据格式为 "GoogleAdsRow"。我没有发现以这种格式呈现的信息有任何用处,而且非常混乱。我想将我的文件打印成基本的 .csv 格式,但据我所知没有任何类型的定界符。到目前为止,我只能将每一整行打印为一个单元格。没有帮助:-)。

我的主要功能如下所示。我提供了两个我尝试过的示例,并在注释块中标识了这两种尝试:

def main(client, customer_id, page_size):
    ga_service = client.get_service('GoogleAdsService', version='v2')

    query = ('SELECT ad_group.id, ad_group_criterion.type, '
             'ad_group_criterion.criterion_id, '
             'ad_group_criterion.keyword.text, '
             'ad_group_criterion.keyword.match_type FROM ad_group_criterion '
             'WHERE ad_group_criterion.type = KEYWORD')

    results = ga_service.search(customer_id, query=query, page_size=page_size)

    try:
        with open(path, "w", encoding = "utf-8", newline = "") as f:
        #with open(path, "w") as csv:
            csv_writer = csv.writer(f, delimiter=',')
            for row in results:
                campaign = row.campaign           
                csv_writer.writerow([row]) #Prints entire returned row as a single cell
                csv_writer.writerow(row) #Tells me there is no delimiter

迭代错误如下

<ipython-input-15-e736ee2d05c9> in main(client, customer_id, page_size)
     17                 campaign = row.campaign
     18                 #csv_writer.writerow([row]) #Prints entire returned row as a single cell
---> 19                 csv_writer.writerow(row) #Tells me there is no delimiter
     20 
     21 

Error: iterable expected, not GoogleAdsRow

您需要分离出返回的各个行项目并将它们分别添加到 CSV 中。每列一个。

根据您的回复,您需要提取返回的 google 行的元素,并将它们放入 CSV 文件中的适当行。

row.campaign.value, 
row.segments.date.value,
row.metrics.cost_micros.value / 1000000,    
row.metrics.clicks.value etc.

不幸的是,您不能直接从 google 行写入 CSV,因为它是一个 protobuff,需要根据需要提取该行的属性。