我使用的是Google Ads SDK for Python。我想获取一些广告数据,并将它们放入一个数据帧中进行一些转换。我使用以下代码进行了调用:
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)下面是我收到的回复:
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我尝试使用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)但是我得到了下面的错误消息:
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'你能帮我弄一下这个吗?谢谢。
发布于 2021-05-16 22:38:01
很抱歉打扰你,但我找到了this question并得到了我的问题的答案。
我将代码更改为以下代码(将._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)而且它起作用了!
https://stackoverflow.com/questions/67557785
复制相似问题