python - Facebook 广告 API - 批量请求定位搜索

标签 python facebook facebook-ads-api


问题:

我在提交 Facebook Ads API 的批量请求时遇到问题,我想知道是否有人可以提供有关以下错误的见解。

我正在尝试获取艺术家列表(在这个简化示例中仅列出 50 名),然后针对这些艺术家提交 TargetingSearch 请求。但是,我无法将请求正确传递到 Facebook。你可以想象我将数千名艺术家传递到这里的情况。

我一直在使用这两个资源在 facebook-ads-api for Python 中批量请求广告/广告集见解作为引用: 奥 git _a https://github.com/facebook/facebook-python-ads-sdk/issues/116

我的代码:

import time
list_of_artists = ['Adele','Alessia Cara','Ariana Grande','Big Sean','Blake Shelton','Brantley Gilbert','Brett Young','Bruno Mars','Calvin Harris','Camila Cabello','Carrie Underwood','Chris Brown','Chris Stapleton','Chuck Berry','Cole Swindell','Dierks Bentley','DJ Khaled','Ed Sheeran','Eminem','Eric Church','Future','G-Eazy','Gucci Mane','James Arthur','Jason Aldean','John Legend','Jon Pardi','Josh Turner','Julia Michaels','Justin Bieber','Justin Timberlake','Katy Perry','Kehlani','Keith Urban','Kelsea Ballerini','Kendrick Lamar','Kenny Chesney','Khalid','Kodak Black','Kygo','Kyle Harvey','Lady Gaga','Lil Yachty','Lorde','Luis Fonsi','Luke Bryan','Luke Combs','Machine Gun Kelly (Rapper)']

def success_callback(response):
    batch_body_responses.append(response.body())

def error_callback(response):
    # Error handling here
    pass

def get_id_list(art_search_list):
    batches = []
    batch_body_responses = []
    your_app_id = '<appid>'
    your_app_secret = '<appsecret>'
    your_access_token = '<token>'
    api = FacebookAdsApi.init(your_app_id, your_app_secret, your_access_token)
    batch_limit = 25
    for batch in generate_batches(art_search_list, batch_limit):
        next_batch = api.new_batch()
        for art in batch:
            requests = TargetingSearch.search(params = {'q': art,'type': 'adinterest'})
            for req in requests:
                # adding a print to see what req looks like
                print req
                next_batch.add_request(req, success_callback, error_callback)
        batches.append(next_batch)

    for batch_request in batches:
        batch_request.execute()
        time.sleep(5)

print batch_body_responses

get_id_list(list_of_artists)

这会导致以下错误:

注意:TargetingSearch 来自上面的打印请求。

<TargetingSearch> {
    "audience_size": 30176300,
    "id": "6003173089178",
    "name": "Adele",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele"
    ],
    "topic": "People"
}
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-299-67aa05ef2228> in <module>()
     33     print batch_body_responses
     34 
---> 35 get_id_list(list_of_artists)
     36 
     37 # # #################

<ipython-input-299-67aa05ef2228> in get_id_list(art_search_list)
     24                 # adding a print to see what req looks like
     25                 print req
---> 26                 next_batch.add_request(req, success_callback, error_callback)
     27         batches.append(next_batch)
     28 

//anaconda/lib/python2.7/site-packages/facebookads/api.pyc in add_request(self, request, success, failure)
    445                 A dictionary describing the call.
    446         """
--> 447         updated_params = copy.deepcopy(request._params)
    448         if request._fields:
    449             updated_params['fields'] = ','.join(request._fields)

AttributeError: 'TargetingSearch' object has no attribute '_params'

如果我能够正确地将批处理传递给 Facebook,我希望得到一个能够为我提供每位艺术家的 TargetingSearch 结果的答案。这是阿黛尔的一个例子,但你可以想象每个人都复制这个例子:

[<TargetingSearch> {
    "audience_size": 30176300,
    "id": "6003173089178",
    "name": "Adele",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele"
    ],
    "topic": "People"
}, <TargetingSearch> {
    "audience_size": 20449710,
    "id": "6003701797690",
    "name": "21 (Adele album)",
    "path": [
        "Interests",
        "Additional Interests",
        "21 (Adele album)"
    ],
    "topic": "News and entertainment"
}, <TargetingSearch> {
    "audience_size": 256080,
    "disambiguation_category": "Song",
    "id": "6005916496872",
    "name": "Someone like You (Adele song)",
    "path": [
        "Interests",
        "Additional Interests",
        "Someone like You (Adele song)"
    ],
    "topic": "News and entertainment"
}, <TargetingSearch> {
    "audience_size": 130230,
    "disambiguation_category": "Home",
    "id": "6002994499323",
    "name": "Adele Live",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele Live"
    ]
}, <TargetingSearch> {
    "audience_size": 31410,
    "disambiguation_category": "Song",
    "id": "6004484416351",
    "name": "Rumour Has It (Adele song)",
    "path": [
        "Interests",
        "Additional Interests",
        "Rumour Has It (Adele song)"
    ],
    "topic": "News and entertainment"
}, <TargetingSearch> {
    "audience_size": 4560,
    "disambiguation_category": "Public Figure",
    "id": "6003446313480",
    "name": "Adele Parks",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele Parks"
    ],
    "topic": "People"
}, <TargetingSearch> {
    "audience_size": 2290,
    "id": "6002970343768",
    "name": "Adele ring",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele ring"
    ],
    "topic": "Education"
}, <TargetingSearch> {
    "audience_size": 990,
    "disambiguation_category": "Musician/Band",
    "id": "6003213600533",
    "name": "Adele - Official Website",
    "path": [
        "Interests",
        "Additional Interests",
        "Adele - Official Website"
    ]
}]

我认为我无法理解如何传递/自定义请求并批量生成可以执行的请求。

-谢谢, 乔丹

最佳答案


我的解决方案(也许还有改进的空间)

我最终找到了解决我问题的方法,它很可能不是最好的,但目前有效。我将最初在下面提交的问题和不正确的代码留在了自己的标题下,以防其他人了解 Facebook API 的批量请求,并发现了解我如何解决此问题很有帮助。

我对首字母缩写的担忧是正确的,我本质上是试图将 TargetingSearch 调用作为请求提交,但实际上它们在作为批处理请求传递之前就已经执行了。

我需要做的是:

  • 使用 FacebookRequest 通过“/targetingsearch”端点创建“GET”请求,然后使用 .add_params 附加查询参数,这些参数会根据批处理中的项目而变化。

  • 在回调函数中添加一些错误处理。某些搜索到的艺术家实际上可能不会返回任何结果,如果您尝试使用索引提取 ID 和名称,则会收到错误。

  • 我选择导入 pandas 并将结果转换为数据框,以便更易于阅读。

提示:故意向 FB 提交错误的调用有助于我排除故障,因为返回的错误消息会向您显示实际发出的请求。

代码:

import time
from facebookads.api import FacebookRequest
import pandas as pd
account = '<act_accountID>'
list_of_artists = ['Adele','Alessia Cara','Ariana Grande','Big Sean','Blake Shelton','Brantley Gilbert','Brett Young','Bruno Mars','Calvin Harris','Camila Cabello','Carrie Underwood','Chris Brown','Chris Stapleton','Chuck Berry','Cole Swindell','Dierks Bentley','DJ Khaled','Ed Sheeran','Eminem','Eric Church','Future','G-Eazy','Gucci Mane','James Arthur','Jason Aldean','John Legend','Jon Pardi','Josh Turner','Julia Michaels','Justin Bieber','Justin Timberlake','Katy Perry','Kehlani','Keith Urban','Kelsea Ballerini','Kendrick Lamar','Kenny Chesney','Khalid','Kodak Black','Kygo','Kyle Harvey','Lady Gaga','Lil Yachty','Lorde','Luis Fonsi','Luke Bryan','Luke Combs','Machine Gun Kelly (Rapper)']

batch_body_responses = []

def success_callback(response):
    try:
        pair = [response.json()["data"][0]["name"],response.json()["data"][0]["id"]]
        batch_body_responses.append(pair)
    except IndexError:
        pass
    except UnicodeEncodeError:
        pass

def error_callback(response):
    pass

def get_id_list(art_search_list):
    batches = []
    your_app_id = '<appid>'
    your_app_secret = '<appsecret>'
    your_access_token = '<token>'
    api = FacebookAdsApi.init(your_app_id, your_app_secret, your_access_token)
    batch_limit = 25
    for batch in generate_batches(art_search_list, batch_limit):
        next_batch = api.new_batch()
        for artt in batch:
            requests = [FacebookRequest(node_id=account,method="GET",endpoint="/targetingsearch").add_params(params = {'q': artt,'type': 'adinterest'})]
            for req in requests:
                next_batch.add_request(req, success_callback, error_callback)
        batches.append(next_batch)

    for batch_request in batches:
        batch_request.execute()
        time.sleep(2)

    return batch_body_responses

df = pd.DataFrame(get_id_list(list_of_artists))
df

结果:

0   Adele   6003173089178
1   Alessia Cara    931161786931155
2   Ariana Grande   6003032339492
3   Big Sean    6002839083879
4   Blake Shelton   6003145416068
5   Brantley Gilbert    6003087234070
6   Young & hip 6006520994425
7   Bruno Mars  6003392437554
8   Calvin Harris   6003700476383
9   Fifth Harmony (Camila Cabello)  173362709468415
10  Carrie Underwood    6003320610294
11  Chris Brown 6003412995205
12  Chris Stapleton 6003632267583
13  Chuck Berry 6003381796604
14  Cole Swindell   6015941143427
15  Dierks Bentley  6003273151043
16  DJ Khaled   6003664971094
17  Ed Sheeran  6003704170491
18  Eminem  6003135347608
19  Eric Church 6003174532035
20  Future  6003289081451
21  G-Eazy  6006359491399
22  Gucci Mane  6003291602130
23  james arthur    6011082407659
24  Jason Aldean    6003138841739
25  John Legend 6003287333056
26  Jon Pardi   6005274491737
27  Josh Turner 6003547807427
28  Justin Bieber   6003143596040
29  Justin Timberlake   6003125864388
30  Katy Perry  6003514925642
31  Kehlani 1673020586319299
32  Keith Urban 6003280487023
33  Kelsea Ballerini    1649934611908779
34  Kendrick Lamar  6003436621883
35  Kenny Chesney   6003183761012
36  Khalid Yasin    6003043109915
37  Kygo    342546012613588
38  List of American Horror Story characters    6014211362622
39  Lady Gaga   6003144466384
40  Lil Yachty  1177170802403085
41  Lorde   6018616059273
42  Luis Fonsi  6003210594524
43  Luke Bryan  6003290279056
44  Machine Gun Kelly (rapper)  6003461497689

关于python - Facebook 广告 API - 批量请求定位搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232666/

相关文章:

python - 将列表元素拆分为键/值字典

python - 对日期序列进行排序的最 pythonic 方法是什么?

php - URL 的重定向过多。在减少重定向数量之前,Facebook 将无法抓取此 URL

ios - 获取 invitable_friends Facebook API iOS

iphone - 如果安装了 IOS 6,则在操作表上显示按钮

facebook-graph-api - 如何使用 FB api 获取推广页面帖子

Facebook 广告 API AdSet 创建规范化错误

python - 如何从写入文件的变量中删除引号?

python - Facebook 广告 API : Retrieving deleted object ids from parent node

python - 在 shell 脚本中检测 python 版本