【问题标题】:What is the data format returned by the AdWords API TargetingIdeaPage service?AdWords API TargetingIdeaPage 服务返回的数据格式是什么?
【发布时间】:2016-04-05 17:14:32
【问题描述】:

当我使用 Python client library 查询 AdWords API 以获取 search volume data and trends through their TargetingIdeaSelector 时,返回的数据如下所示:

(TargetingIdeaPage){
       totalNumEntries = 1
       entries[] = 
          (TargetingIdea){
             data[] = 
                (Type_AttributeMapEntry){
                   key = "KEYWORD_TEXT"
                   value = 
                      (StringAttribute){
                         Attribute.Type = "StringAttribute"
                         value = "keyword phrase"
                      }
                },
                (Type_AttributeMapEntry){
                   key = "TARGETED_MONTHLY_SEARCHES"
                   value = 
                      (MonthlySearchVolumeAttribute){
                         Attribute.Type = "MonthlySearchVolumeAttribute"
                         value[] = 
                            (MonthlySearchVolume){
                               year = 2016
                               month = 2
                               count = 2900
                            },
                            ...
                            (MonthlySearchVolume){
                               year = 2015
                               month = 3
                               count = 2900
                            },
                      }
                },
          },
     }

这不是 JSON,看起来只是一个凌乱的 Python 列表。将每月数据扁平化为具有这种结构的 Pandas 数据框的最简单方法是什么?

Keyword         |  Year  | Month | Count
 keyword phrase    2016      2       10

【问题讨论】:

    标签: python pandas google-ads-api


    【解决方案1】:

    输出是一个 sudsobject。我发现这段代码可以解决问题:

    import suds.sudsobject as sudsobject
    import pandas as pd
    a = [sudsobject.asdict(x) for x in output]
    df = pd.DataFrame(a)
    

    附录:这曾经是正确的,但 API 的新版本(我测试过 201802) 现在返回 zeep.objects。然而, zeep.helpers.serialize_object 应该做同样的伎俩。 link

    【讨论】:

    • 对不起,我的延迟回复!感谢您的解释!完成这项工作的代码要简单得多!
    【解决方案2】:

    这是我用来查询 TargetingIdeaSelector 的完整代码,带有 requestType STATS,以及我用来将数据解析为可用数据帧的方法;请注意开始“将结果解析为 pandas 数据帧”的部分,因为这会获取上述问题中给出的输出并将其转换为数据帧。可能不是最快或最好的,但它确实有效!使用 Python 2.7 测试。

    """This code pulls trends for a set of keywords, and parses into a dataframe.
    
    The LoadFromStorage method is pulling credentials and properties from a
    "googleads.yaml" file. By default, it looks for this file in your home
    directory. For more information, see the "Caching authentication information"
    section of our README.
    
    """
    
    from googleads import adwords
    import pandas as pd
    
    
    adwords_client = adwords.AdWordsClient.LoadFromStorage()
    
    PAGE_SIZE = 10
    
    # Initialize appropriate service.
    targeting_idea_service = adwords_client.GetService(
        'TargetingIdeaService', version='v201601')
    
    # Construct selector object and retrieve related keywords.
    offset = 0
    stats_selector = {
        'searchParameters': [
            {
                'xsi_type': 'RelatedToQuerySearchParameter',
                'queries': ['donald trump', 'bernie sanders']
            },
            {
            # Language setting (optional).
            # The ID can be found in the documentation:
            #  https://developers.google.com/adwords/api/docs/appendix/languagecodes
                'xsi_type': 'LanguageSearchParameter',
                'languages': [{'id': '1000'}],
            },
            {
                # Location setting
                'xsi_type': 'LocationSearchParameter',
                'locations': [{'id': '1027363'}]  # Burlington,Vermont
            }
        ],
        'ideaType': 'KEYWORD',
        'requestType': 'STATS',
        'requestedAttributeTypes': ['KEYWORD_TEXT', 'TARGETED_MONTHLY_SEARCHES'],
        'paging': {
            'startIndex': str(offset),
            'numberResults': str(PAGE_SIZE)
        }
    }
    
    stats_page = targeting_idea_service.get(stats_selector)
    
    
    ##########################################################################
    # Parse results to pandas dataframe
    
    
    stats_pd = pd.DataFrame()
    
    if 'entries' in stats_page:
        for stats_result in stats_page['entries']:
            stats_attributes = {}
            for stats_attribute in stats_result['data']:
                #print (stats_attribute)
                if stats_attribute['key'] == 'KEYWORD_TEXT':
                    kt = stats_attribute['value']['value']
                else:
                    for i, val in enumerate(stats_attribute['value'][1]):                
                        data = {'keyword': kt,
                                'year': val['year'],
                                'month': val['month'],
                                'count': val['count']}
                        data = pd.DataFrame(data, index = [i])                
                        stats_pd = stats_pd.append(data, ignore_index=True)
    
    
    print(stats_pd)
    

    【讨论】:

    • 此代码是否使用通过测试帐户生成的凭据?如果是这样,结果是否有意义?在其他地方,我读到测试帐户会产生“虚拟”数据。谢谢-克里斯
    • 我用的是真实账户,数据肯定是有意义的。我无法评论您使用测试帐户时会发生什么。也就是说,我确实担心您需要使用“真实”帐户,因为尚不清楚帐户设置可能(或可能不会)影响返回的结果。
    • 谢谢。我的理解是,测试帐户返回虚拟结果是因为 Google 限制对真实数据的访问,以防止滥用/违反 TOS 等。
    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 2012-09-19
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2014-06-09
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多