import re import sys import pandas as pd import requests #pip install criteo_marketing --https://pypi.org/project/criteo-marketing/ import criteo_marketing as cm from criteo_marketing import Configuration #pip install facebook_business --https://pypi.org/project/facebook-business/ from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount #pip install google-api-python-client --https://pypi.org/project/google-api-python-client/ from apiclient.discovery import build #pip install oauth2client --https://pypi.org/project/oauth2client/ from oauth2client.service_account import ServiceAccountCredentials import datetime from datetime import timedelta #Enter the Date Range You want to Run for startdate='2021-04-20' enddate='2021-04-26' #Convert To Date Format vstartdate=datetime.datetime.strptime(startdate,'%Y-%m-%d') venddate=datetime.datetime.strptime(enddate,'%Y-%m-%d') delta = timedelta(days=1) app_id = 'Your AP ID' app_secret = 'Your app_secret' access_token = 'Your access_token' FacebookAdsApi.init(app_id, app_secret, access_token,api_version='v9.0') #Create a File for Each Date while vstartdate <=venddate : params = { 'time_range': {'since': str(vstartdate.date()), 'until': str(vstartdate.date())}, 'time_increment': 1, # <== daily data mechanism 'level': 'campaign' } fields = ['account_name', 'campaign_name', 'clicks', 'cpm', 'ctr', 'date_start', 'date_stop', 'spend', 'impressions',] insights = AdAccount('act_').get_insights(params = params, fields = fields) headers = ["account_name,", "campaign_name,", "clicks,", "cpm,", "ctr,", "date_start,", "date_stop,", "impressions,", "spend"] #Print Empty if No Data if not insights: print('Empty') #Create Files If Data else: #Add Header to the File with open(r'C:\Inbound\fb_campaign_output_'+str(vstartdate.date()).replace('-', '')+'.txt', 'w', encoding='utf-8') as writeheader: writeheader.write("\t".join(headers)+"\n") writeheader.close #Add Rows to File with open(r'C:\Inbound\fb_campaign_output_'+str(vstartdate.date()).replace('-', '')+'.txt', 'a') as text_file: for row in insights: print(insights) text_file.write(row['account_name']+','+row['campaign_name']+','+row['clicks']+','+row['cpm']+','+row['ctr']+','+row['date_start']+','+row['date_stop']+','+row['impressions']+','+row['spend']+'\n') print(vstartdate.date()) vstartdate =vstartdate+delta