【发布时间】:2018-06-25 20:39:42
【问题描述】:
我正在使用 Facebook 营销 API 为我的公司报告。我需要开始获取广告的目标 URL,以将支出数据与正确的广告组(存储在我们的个人数据库中)相关联。但是,当我进行此额外调用时,它是针对不支持异步的报告,并且我们很快达到了速率限制。关于如何将 AdInsights 和创意信息简化为一个电话的任何想法?或者减轻广告素材信息的负担?
# This program downloads all relevant Facebook traffic info as a csv file
# This program requires info from the Facebook Ads API: https://github.com/facebook/facebook-python-ads-sdk
# Import all the facebook mumbo jumbo
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.business import Business
from facebookads.adobjects.adreportrun import AdReportRun
from facebookads.adobjects.adcreative import AdCreative
# Import th csv writer and the date/time function
import datetime
from datetime import date
import time
from datetime import timedelta
import csv
import string
# Set the info to get connected to the API. Do NOT share this info
my_app_id = '***'
my_app_secret = '***'
my_access_token = '***'
# Start the connection to the facebook API
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
# Create a business object for the *** business account
#business = Business('***')
# Get yesterday's date for the filename, and the csv data
yesterdayday = date.today() - timedelta(days=1)
yesterdayhyphen = (yesterdayday).strftime('%Y-%m-%d')
# Define the destination filename
filename = yesterdayhyphen + '_fb.csv'
filelocation = "/cron/downloads/"+ filename
# Get all ad accounts on the business account
#accounts = business.get_owned_ad_accounts(fields=[AdAccount.Field.id])
accounts = ['act_***', 'act_***', 'act_***', 'act_***', 'act_***', 'act_***', 'act_***', 'act_***']
# Open or create new file
try:
csvfile = open(filelocation , 'w+', 0777)
except:
print ("Cannot open file.")
# To keep track of rows added to file
rows = 0
try:
# Create file writer
filewriter = csv.writer(csvfile, delimiter=',')
except Exception as err:
print(err)
# Iterate through the adaccounts
for account in accounts:
# Create an addaccount object from the adaccount id to make it possible to get insights
#tempaccount = AdAccount(account[AdAccount.Field.id])
tempaccount = AdAccount(account)
# Grab insight info for all ads in the adaccount
ads = tempaccount.get_insights(params = {'level' : 'ad',
'date_preset' : 'yesterday' },
fields = [AdsInsights.Field.account_id,
AdsInsights.Field.account_name,
AdsInsights.Field.ad_id,
AdsInsights.Field.ad_name,
AdsInsights.Field.adset_id,
AdsInsights.Field.adset_name,
AdsInsights.Field.campaign_id,
AdsInsights.Field.campaign_name,
AdsInsights.Field.cost_per_outbound_click,
AdsInsights.Field.outbound_clicks,
AdsInsights.Field.spend],
async = True)
ads.remote_read()
while ((ads[AdReportRun.Field.async_percent_completion] < 100) and (ads[AdReportRun.Field.async_status] != "Job Completed")):
time.sleep(1)
ads.remote_read()
time.sleep(1)
ads = ads.get_result()
print(ads)
adcreatives = tempaccount.get_ad_creatives(params = {'level' : 'ad',
'date_preset' : 'yesterday'},
fields = [AdCreative.Field.object_story_spec])
# Iterate through all accounts in the business account
for ad in ads:
# Set default values in case the insight info is empty
date = yesterdayhyphen
accountid = ad[AdsInsights.Field.account_id]
accountname = ""
adid = ""
adname = ""
adsetid = ""
adsetname = ""
campaignid = ""
campaignname = ""
costperoutboundclick = ""
outboundclicks = ""
spend = ""
destinationurl = ""
# Set values from insight data
if ('account_id' in ad) :
accountid = ad[AdsInsights.Field.account_id]
if ('account_name' in ad) :
accountname = ad[AdsInsights.Field.account_name]
if ('ad_id' in ad) :
adid = ad[AdsInsights.Field.ad_id]
if ('ad_name' in ad) :
adname = ad[AdsInsights.Field.ad_name]
if ('adset_id' in ad) :
adsetid = ad[AdsInsights.Field.adset_id]
if ('adset_name' in ad) :
adsetname = ad[AdsInsights.Field.adset_name]
if ('campaign_id' in ad) :
campaignid = ad[AdsInsights.Field.campaign_id]
if ('campaign_name' in ad) :
campaignname = ad[AdsInsights.Field.campaign_name]
if ('cost_per_outbound_click' in ad) : # This is stored strangely, takes a few steps to break through the layers
costperoutboundclicklist = ad[AdsInsights.Field.cost_per_outbound_click]
costperoutboundclickdict = costperoutboundclicklist[0]
costperoutboundclick = costperoutboundclickdict.get('value')
if ('outbound_clicks' in ad) : # This is stored strangely, takes a few steps to break through the layers
outboundclickslist = ad[AdsInsights.Field.outbound_clicks]
outboundclicksdict = outboundclickslist[0]
outboundclicks = outboundclicksdict.get('value')
if ('spend' in ad) :
spend = ad[AdsInsights.Field.spend]
for adcreative in adcreatives:
if ( ad[AdsInsights.Field.ad_id] == adcreative[ 'id' ] ):
destinationurl = adcreative[AdCreative.Field.object_story_spec.link_url]
# Write all ad info to the file, and increment the number of rows that will display
filewriter.writerow([date, accountid, accountname, adid, adname, adsetid, adsetname, campaignid, campaignname, costperoutboundclick, outboundclicks, spend, destinationurl])
rows += 1
csvfile.close()
# Print report
print (str(rows) + " rows added to the file " + filelocation)
【问题讨论】:
标签: python facebook asynchronous facebook-marketing-api