Facebook Marketing API - 获取洞察力的Python - 达到用户请求限制

问题描述 投票:4回答:3

因此,我正在尽我所能通过Facebook API。我需要创建一个脚本,每天下载我的业务活动信息作为csv文件,这样我就可以使用另一个脚本轻松地将信息上传到我们的数据库。

我终于有了用于将信息打印到日志的代码,但我达到了用户请求限制,因为我必须单独为每个广告系列调用get_insights()。我想知道是否有人知道如何帮助我这样做,所以我不必经常调用facebook API。

如果找到一个我可以获得每日花费的字段,我想做什么,所以我不必在我的竞选循环的每一次迭代中调用API,但我不能为我的生活找到一种方法这样做。

#Import all the facebook mumbo jumbo
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.adobjects.adreportrun import AdReportRun
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.business import Business
import time

#Set the login 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)

business = Business('****')

#Get all ad accounts on the business account 
accounts = business.get_owned_ad_accounts(fields=[AdAccount.Field.id])

#iterate through all accounts in the business account
for account in accounts:
    tempaccount = AdAccount(account[AdAccount.Field.id])
    #get all campaigns in the adaccount
    campaigns = tempaccount.get_campaigns(fields=[Campaign.Field.name,Campaign.Field])
    #iterate trough all the campaigns in the adaccount
    for campaign in campaigns:
        print(campaign[Campaign.Field.name])
        #get the insight info (spend) from each campaign
        campaignsights = campaign.get_insights(params={'date_preset':'yesterday'},fields=[AdsInsights.Field.spend])
        print (campaignsights)
python facebook-graph-api facebook-insights facebook-marketing-api
3个回答
5
投票

花了一段时间挖掘API并猜测,但我明白了!这是我的最终剧本:

# This program downloads all relevent 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

# Import th csv writer and the date/time function
import datetime
import csv

# 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
yesterdaybad = datetime.datetime.now() - datetime.timedelta(days=1)
yesterdayslash = yesterdaybad.strftime('%m/%d/%Y')
yesterdayhyphen = yesterdaybad.strftime('%m-%d-%Y')

# 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])

# 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])

    # Grab insight info for all ads in the adaccount
    ads = tempaccount.get_insights(params={'date_preset':'yesterday',
                                           'level':'ad'
                                          },
                                   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
                                          ]
    );

    # Iterate through all accounts in the business account
    for ad in ads:
        # Set default values in case the insight info is empty
        date = yesterdayslash
        accountid = ad[AdsInsights.Field.account_id]
        accountname = ""
        adid = ""
        adname = ""
        adsetid = ""
        adsetname = ""
        campaignid = ""
        campaignname = ""
        costperoutboundclick = ""
        outboundclicks = ""
        spend = ""

        # 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]

        # 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])
        rows += 1


csvfile.close()

# Print report
print (str(rows) + " rows added to the file " + filename)

然后我有一个PHP脚本,它接受csv文件并将其上传到我的数据库。关键是将所有洞察数据拉到一个大块中。然后,您可以根据需要对其进行细分,因为每个广告都包含有关其adset,adaccount和广告系列的信息。


2
投票

添加一些小功能来改善LucyTurtle的答案,因为它仍然容易受到Facebook的速率限制

import logging
import requests as rq

#Function to find the string between two strings or characters
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

#Function to check how close you are to the FB Rate Limit
def check_limit():
    check=rq.get('https://graph.facebook.com/v3.1/act_'+account_number+'/insights?access_token='+my_access_token)
    usage=float(find_between(check.headers['x-ad-account-usage'],':','}'))
    return usage

#Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your 'for ad is ads' loop, every 100-200 iterations)
if (check_limit()>75):
    print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
    time.sleep(300)

0
投票

我想说谢谢你。正如马克斯安德烈所说 - 你创造了我的一天! FB SDK文档是详尽无遗的,但它完全没有像这样的日常任务的实际实现示例。书签已设置 - 页面将很快重新访问。

因此,我唯一可以为其他受害者做出贡献的是:似乎使用较新的facebook_business SDK,您只需将导入语句中的“facebookads”替换为“facebook_business”。

© www.soinside.com 2019 - 2024. All rights reserved.