将 Google Ads API 结果放入 Dataframe 中

Toà*_*oàn 5 python google-ads-api

我正在使用适用于 Python 的 Google Ads API SDK。我想获取一些广告数据并将它们放入 Dataframe 中进行一些转换。我用下面的代码拨打了电话:

client = GoogleAdsClient.load_from_storage("config.yaml")
customer_id = '<customer_id>'
ga_service = client.get_service("GoogleAdsService")
query = """
    SELECT
        campaign.id,
        campaign.name,
        customer.id
    FROM campaign
    """
response = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in response:
    for row in batch.results:
        print(row)
        df = pd.DataFrame(row)
        print(df)
Run Code Online (Sandbox Code Playgroud)

这是我收到的回复:

customer {
  resource_name: "customers/<customer-id>"
  id: <customer-id>
}
campaign {
  resource_name: "customers/<customer-id>/campaigns/<campaign-id>"
  name: "Test_campaign_1"
  id: <campaign-id>
}

Traceback (most recent call last):
  File "c:\Users\User\main.py", line 36, in <module>
    print(dict(row))
TypeError: 'GoogleAdsRow' object is not iterable
Run Code Online (Sandbox Code Playgroud)

我尝试使用 google.protobuf.json_format 将结果转换为 json/dict 格式,代码如下

from google.protobuf.json_format import MessageToJson
response = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in response:
    for row in batch.results:
        print(row)
        jsonobj = MessageToJson(row)
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误消息:

  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\proto\message.py", line 605, in __getattr__
    raise AttributeError(str(ex))
AttributeError: 'DESCRIPTOR'
Run Code Online (Sandbox Code Playgroud)

你能帮我解决这个问题吗?谢谢。

Toà*_*oàn 4

抱歉打扰,但我找到了这个问题并得到了我的问题的答案。

我将代码更改为以下(将 ._pb 添加到响应中):

response = ga_service.search(customer_id=customer_id, query=query)
dictobj = MessageToDict(response._pb)
df = pd.json_normalize(dictobj,record_path=['results'])
print(df)
Run Code Online (Sandbox Code Playgroud)

它有效!