Skip to content

Instantly share code, notes, and snippets.

@darthsuogles
Last active November 8, 2017 18:46
Show Gist options
  • Save darthsuogles/fcd00c019af892fa9a533e5839d699b7 to your computer and use it in GitHub Desktop.
Save darthsuogles/fcd00c019af892fa9a533e5839d699b7 to your computer and use it in GitHub Desktop.
Get Facebook graph API calls
from time import sleep
from random import randint
import json
import requests
import pandas as pd
def fb_graph_api_crawl(params, **kws):
print('initial call')
res = requests.get('https://graph.facebook.com/v2.8/search', params).json()
_js_list = [res['data']]
_r_sleep_min = 4
try: _r_sleep_min = kws['sleep_min']
except: pass
_r_sleep_max = 12
try: _r_sleep_max = kws['sleep_max']
except: pass
def _pause(): sleep(randint(_r_sleep_min, _r_sleep_max))
while 'paging' in res:
_pause()
print('next page', res['paging']['cursors'])
res = requests.get(res['paging']['next']).json()
_js_list.append(res['data'])
return pd.concat(map(pd.DataFrame, _js_list))
df_geoloc = fb_graph_api_crawl({
'type': 'adgeolocation',
'location_types': ['geo_market'],
'access_token': APP_TOKEN
})
df_geoloc.to_csv('fb_ad_geolocations.csv')
df_demint = fb_graph_api_crawl({
'type': 'adTargetingCategory',
'class': 'interests',
'access_token': APP_TOKEN
})
df_demint.to_csv('fb_ad_target_demo_interests.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment