Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.4 kB
3
Indexable
Never
import requests
import csv

def fetch_ad_hierarchy(access_token, account_id):
    base_url = f"https://graph.facebook.com/v18.0/act_{account_id}/campaigns"
    fields_list = [
        'name',
        'adsets{name,ads{name,adcreatives{name,image_url},insights{reach,impressions,clicks,ctr,spend,cpc,cpm,cpp,frequency,inline_post_engagement,objective,buying_type}}}'
    ]
    params = {
        'access_token': access_token,
        'fields': ','.join(fields_list),
        'limit': 1000
    }
    response = requests.get(base_url, params=params)
    return response.json() if response.status_code == 200 else None

def save_to_csv(data, filename):
    with open(filename, 'w', newline='') as csvfile:
        fieldnames = ['campaign_name', 'adset_name', 'ad_name',
                      'reach', 'impressions', 'clicks', 'ctr', 'spend',
                      'cpc', 'cpm', 'cpp', 'frequency', 'inline_post_engagement',
                      'objective', 'buying_type']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        for campaign in data:
            campaign_name = campaign.get('name')
            for adset in campaign.get('adsets', {}).get('data', []):
                adset_name = adset.get('name')
                for ad in adset.get('ads', {}).get('data', []):
                    ad_name = ad.get('name')
                    insights = ad.get('insights', {}).get('data', [{}])[0]
                    writer.writerow({
                        'campaign_name': campaign_name,
                        'adset_name': adset_name,
                        'ad_name': ad_name,
                        **{key: insights.get(key, '') for key in fieldnames[3:]}
                    })

# Provided credentials and account IDs:
access_token = 'EAARaOzsc16cBO9uZC74vnE9pde2cBkH4ulZBZAnVWt90fapHZCFQSxnJ6UEEHkuqEMyFc19KbKKpf0uyPajkhSxMQZBdYq1tGLNoTn0ZAGfjEF28KsZAlVBxuLmylCZCVjl2HhhpkyYT1In37pYo7aJ76pVBthV05owZBXJMGc5ot1JO38pxFfqZAu7y0Ix82aZBHZBwlzKjy5ZCaspG3GOUFhyqsglsC'
account_ids = [
    '1173712960044374', '584778626845706', '590246856448763', '374062838062049',
    '518001613125358', '3206214186258420', '198353962484088', '364329008672466', '115751749866648'
]

# Fetching and saving the data for each account ID:
for account_id in account_ids:
    data = fetch_ad_hierarchy(access_token, account_id)
    if data:
        save_to_csv(data.get('data', []), f'ad_insights_{account_id}.csv')