Created
August 13, 2011 16:51
-
-
Save starenka/1144026 to your computer and use it in GitHub Desktop.
gets page likes and category via fb api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# @depends: pip install git+git://github.com/facebook/python-sdk.git#egg=facebook | |
import sys, time, datetime, csv, logging, os | |
from optparse import OptionParser | |
import facebook | |
usage = "python facepalm.py -i /where/to/get/input/file" | |
parser = OptionParser(usage) | |
parser.add_option('-s', '--sleep', action='store', dest='sleep', default=1, help='sleep (secs) between queries') | |
parser.add_option('-i', '--input-file', action='store', dest='input', default=False, help='input file') | |
(options, args) = parser.parse_args() | |
logger = logging.getLogger('facepalm') | |
logging.basicConfig(format="%(asctime)-15s %(name)s:%(levelname)s %(message)s") | |
logger.setLevel(logging.INFO) | |
if not options.input: | |
sys.exit('No input file provided. See python facepalm.py --help') | |
GET = ('likes', 'category', 'id') | |
logger.info('Parsing file "%s"' % options.input) | |
try: | |
input = open(options.input, 'r').read() | |
lines = input.splitlines() | |
except Exception, e: | |
logger.error('Failed to parse input file. Is it readable/did you provide right path?') | |
sys.exit() | |
try: | |
out_name = '%s/facepalm/%s.csv' % (os.path.expanduser('~'), datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')) | |
out_file = open(out_name, 'w+') | |
logger.info('Creating output file "%s"' % out_name) | |
out = csv.writer(out_file, delimiter=',', quotechar='"') | |
except Exception, e: | |
logger.error('Failed to create out file %s. Check perms. (%s)' % (out_name, e)) | |
sys.exit() | |
graph = facebook.GraphAPI() | |
out.writerow(['uri'] + list(GET)) | |
try: | |
for one in lines: | |
logger.info('Sleeping for %d sec to avoid API throttling.' % options.sleep) | |
time.sleep(int(options.sleep)) | |
logger.info('Getting %s' % one) | |
try: | |
obj = graph.get_object('/%s' % one.split('/')[-1]) | |
gimme = [one] + [obj[get] for get in GET] | |
except Exception, e: | |
logger.error('Failed to get data from %s. Moving to next. (%s)' % (one, e)) | |
continue | |
logger.info('Writing data to csv %s' % gimme) | |
out.writerow(gimme) | |
logger.info('All done. Get your cookies at %s' % out_name) | |
except KeyboardInterrupt: | |
out_file.close() | |
sys.exit('Bye ;)') | |
except Exception, e: | |
logging.error('Failed misarable :( (%s)' % e) | |
finally: | |
out_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment