当前位置: 首页 > 面试题库 >

Facebook Marketing API-通过Python获取见解-达到用户请求限制

籍昱
2023-03-14
问题内容

因此,我正在竭尽全力在Facebook
API中导航。我需要创建一个脚本,该脚本每天将以csv文件的形式下载我公司的广告系列信息,因此我可以使用另一个脚本轻松地将该信息上传到我们的数据库中。

我终于有了可以将信息打印到日志的代码,但是由于用户必须分别为每个单个活动调用get_insights(),因此我达到了用户请求的限制。我想知道是否有人知道如何帮助我做到这一点,所以我不必经常调用facebook
API。

如果我找到一个可以获取每日支出的字段,那么我该怎么办,这样我就不必在for Campaign循环的每次迭代中都调用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)

问题答案:

花了一段时间浏览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)

然后,我有了一个使用csv文件并将其上传到我的数据库的php脚本。关键是将所有洞察力数据汇总在一起。然后,您可以根据需要将其分解,因为每个广告都具有有关其广告集,帐户和广告系列的信息。



 类似资料:
  • 根据CloudFront的文档(https://docs.aws.amazon.com/amazoncloudfront/latest/developerguide/requestandresponseBehaviorCustomOrigin.html),客户端IP可以是头的前面、中间和结尾。 是Rignt吗?那我怎么才能得到真正的客户端IP呢?

  • 我有一个Web角前端,API网关受Cognito和Lambda保护,用于其他业务用例。登录和授权工作正常。我正在使用AWS Javascript SDK进行授权。像https://s3.amazonaws.com/solutions-reference/mobile-backend/latest/mobile-app-backend.pdf 在我的lambda中,我需要获得其他用户的信息,如名字、

  • 如何获取json请求正文?

  • 问题内容: 我通过JavaScript收到了带有AJAX请求的JSON响应。 这是响应: 我的目标是获取内容: json变量是我的情况下的数据。因此,我尝试了: 但是我得到一个空字符串。 关于如何访问字符串的任何想法? 先感谢您。 问题答案: 您是否首先解析json? 比阅读

  • 我有一个正在解析的用户列表。通用域名格式 我需要检索其中一些用户,我有所有必要的ID。例如,parse中存储了50个用户,但我只需要10个。 有了这10个ID,我需要获得用户。 我是邮递员,我做下一件事: 我得到了正确的数据。 如何将其转换为改装呼叫?如何在改装中使用“where”语句? 感谢所有。

  • 网页通过http接口请求,如何获取用户内网ip?