I can't fetch stats for all my facebook campaigns using Python and Facebook Marketing API

↘锁芯ラ 提交于 2019-12-25 02:56:30

问题


I'm trying to retrieve the following metrics: date, campaign_name, impressions, clicks & spend, of all the campaigns in my facebook account but apparently the script I wrote returns only stats for some campaigns and not all of them. It returns only the campaign_name and its id for most of the campaigns.

I'm having this doubt that it only returns the stats for active campaigns and not the inactive ones. Anyone knows how I can mention that I always want to fetch inactive/paused campaigns?

Here is the the script I'm using:

import requests
import json

token = 'MY TOKEN'
act_id = 'MY ACCOUNT ID'
first_request = 'https://graph.facebook.com/v3.2/act_id/campaigns?fields=created_time,name,insights{spend,impressions,clicks}&access_token=%s'%token

Then I run the following:

campaigns=[]
current_request = first_request
while True:
  result = requests.get(current_request)
  content_dict = json.loads(result.content)
  for x in content_dict['data']:
    campaigns.append(x)
  if 'next' in content_dict['paging']:
    m = content_dict['paging']['next'].find('&after')
    current_request = first_+content_dict['paging']['next'][m:]
    print('next request: ', current_request)
  else:
    break

A sample of the output (first campaigns with the desired stats, and second without) :

[{'created_time': '2019-03-29T12:00:29+0100',
  'id': '6133534332561',
  'insights': {'data': [{'clicks': '199',
     'date_start': '2019-03-03',
     'date_stop': '2019-04-01',
     'impressions': '35749',
     'spend': '71.44'}],
   'paging': {'cursors': {'after': 'MAZDZD', 'before': 'MAZDZD'}}},
  'name': '20190422-FB-BOOST-DSDS-CC JHISO- 2 - SDSDDE'},
{'created_time': '2019-01-31T16:06:01+0100',
  'id': '434465343233',
  'name': '20190204-FB-BOOST-SQ-CC FDSSZ- 3EEZK'}]

来源:https://stackoverflow.com/questions/55469743/i-cant-fetch-stats-for-all-my-facebook-campaigns-using-python-and-facebook-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!