我一直在努力关闭使用Python和Facebook营销API在Adset中表现不佳的Facebook广告。我有点担心我的代码对API的访问次数。另一个问题是我使用'get_insights'方法来访问我想用来构建逻辑决策的参数,但我需要使用'get_ads'来打开/关闭它们,所以我觉得我做的事情增加了一倍。 这是我到目前为止使用API v2.9做的一个例子:
from facebookads.api import FacebookAdsApi
from facebookads import adobjects
from facebookads.adobjects.adaccount import *
from facebookads.adobjects.campaign import *
from facebookads.adobjects.adset import *
from facebookads.adobjects.ad import *
from fctn import * # this is just a file where I centralized some functions
import credentials
import copy
# Auth
my_app_id = credentials.my_app_id
my_app_secret = credentials.my_app_secret
my_access_token = credentials.my_access_token
api = FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
ad_account = AdAccount(credentials.ad_account)
# Batch creation
my_batch = api.new_batch()
# Desired fields
fields = ['campaign_name', 'adset_name', 'ad_name', 'ctr', 'impressions']
# Getting all Adsets
ad_sets = ad_account.get_ad_sets(fields=[AdSet.Field.name, Ad.Field.created_time, Ad.Field.status],
params={
'effective_status': ['ACTIVE'],
'date_preset': 'last_30d',
'limit': 5000})
# We'll iterate over each adset because we want to campare just the ads inside the same adset
for ad_set in ad_sets:
ads = ad_set.get_ads(fields=[Ad.Field.name, Ad.Field.created_time, Ad.Field.status],
params={'effective_status': ['ACTIVE'],
'date_preset': 'last_30d',
'limit': 5000})
ads_insights = ad_set.get_insights(fields=fields,
params={'level': 'ad',
'date_preset': 'last_30d',
'effective_status': ['ACTIVE'],
'limit': 5000})
# this is an external funtion to get the median in relation with some metric
median_ctr = median_metric(ads_insights, 'ctr')
print(median_ctr)
print(ads_insights[0]['campaign_name'])
print(ad_set['name'])
print('BEFORE')
print(ads)
for i in range(0, len(ads)):
if dias_ate_hoje(ads[i]['created_time'][:10]) < 10:
# If Ad running less than 10 days, keep going
continue
else:
if float(ads_insights[i]['impressions']) < 300:
# If impressions less then 300, keep going (just an arbitrary decision here)
continue
else:
if float(ads_insights[i]['ctr']) < median_ctr:
# If Ad is in the worst half in relation with CTR: turn off
ads[i].api_update(params={'status': 'PAUSED'}, batch=my_batch)
else:
continue
my_batch.execute()
print('AFTER')
print(ads)
希望任何已经做过类似事情的人可以帮助我更好地使用这些代码,同时减少对API的访问和双倍的代码。 感谢。
答案 0 :(得分:0)
这是你可以做的:
ad_account.get_ads()
ad_account.get_insights(fields=fields,params={'level': 'ad', ...})
在您的见解API调用中,您需要将adset_id
和ad_id
添加到fields
,以便您可以计算广告中位数和暂停广告。
通过这种方式,您不需要遍历广告并为每个广告设置API调用。如果洞察数据太大,您可以尝试使用async insights api https://developers.facebook.com/docs/marketing-api/insights/best-practices#asynchronous