1

看看这段代码

order_service = client.GetService('OrderService', version='v201208')
creative_service = client.GetService('CreativeService', version='v201208')
with open('/tmp/urls.txt', 'w') as f:
    for i in range(0, 3929, 100):
        print 'ORDER BY ID LIMIT 100 OFFSET '+str(i)
        creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 100 OFFSET '+str(i)})
        try:
            for creative in creatives[0]['results']:
                try:
                    for var in creative['creativeTemplateVariableValues']:
                        if var['uniqueName'] == 'DetailsPageURL':                           
                            print var['value']
                            f.write(creative['advertiserId']+','+var['value']+"\n")
                exception:
                    pass
        except:
            raise
            pass

当偏移量为 200 时的第二次迭代,将抱怨for creative in creatives[0]['results']结果 keyerror,但如果我将 try/except 语句更改为if creative.has_key('creativeTemplateVariableValues'):如下所示,则可以解决问题:

order_service = client.GetService('OrderService', version='v201208')
creative_service = client.GetService('CreativeService', version='v201208')
with open('/tmp/urls.txt', 'w') as f:
    for i in range(0, 3929, 100):
        print 'ORDER BY ID LIMIT 100 OFFSET '+str(i)
        creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 100 OFFSET '+str(i)})
        try:
            print creatives[0]['results']
        except:
            print creatives
        #creatives = creative_service.getCreativesByStatement({'query':'ORDER BY ID LIMIT 10 OFFSET 200'})
        try:
            for creative in creatives[0]['results']:
                if creative.has_key('creativeTemplateVariableValues'):
                    for var in creative['creativeTemplateVariableValues']:
                        if var['uniqueName'] == 'DetailsPageURL':
                            print var['value']
                            f.write(creative['advertiserId']+','+var['value']+"\n")
        except:
            raise
            pass

为什么???

4

1 回答 1

1

字段“creativeTemplateVariableValues”是“TemplateCreative”类型的广告素材,因此如果您的网络上有其他不是 TemplateCreative 的广告素材,它将没有该字段并引发您所看到的关键错误。您可以像以前一样进行 has_key 检查,或者另一种方法是进行类型检查:

if creative['Creative_Type'] == 'ImageCreative':
  for var in creative['creativeTemplateVariableValues']:
    ...

如果您只关心 TemplateCreatives,我建议您使用针对该特定广告素材类型的语句过滤器。请参阅 get_creatives_by_statement 示例 (http://code.google.com/p/google-api-ads-python/source/browse/trunk/examples/adspygoogle/dfp/v201208/get_creatives_by_statement.py)

有关 DFP API 和相关客户端库的未来问题,请发布到 DFP API 论坛:https ://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api

于 2012-11-28T22:36:30.280 回答