Advertisement
johnmahugu

PYTHON >>> Twitter API SQLite

May 6th, 2016
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. import twitter
  2. import sqlite3
  3. import os
  4. from datetime import datetime
  5.  
  6. # Set the Twitter API authentication
  7. api = twitter.Api(consumer_key='your-key',
  8.                   consumer_secret='your-secret-key',
  9.                   access_token_key='your-access-token',
  10.                   access_token_secret='your-token-secret')
  11.  
  12. # These are the accounts for which you will fetch data
  13. # It's a list of lists, with a category added for each handle
  14. handles_list = [
  15.     ['chrisschnaars', 'journalist'],
  16.     ['anthonydb', 'journalist'],
  17.     ['usatoday', 'newsroom']
  18. ]
  19.  
  20. # Function to add row to accounts table
  21. def insert_db(handle, category, followers, description):
  22.     conn = sqlite3.connect('social_data2.db')
  23.     cur = conn.cursor()
  24.     cur.execute('''
  25.        INSERT INTO twaccounts VALUES (?,?,?,?,?);
  26.        ''', (datetime.now(), handle, category, followers, description))
  27.     conn.commit()
  28.     conn.close()
  29.  
  30. # Create the database if it doesn't exist
  31. if not os.path.exists('social_data2.db'):
  32.     conn = sqlite3.connect('social_data2.db')
  33.     conn.close()
  34. else:
  35.     pass
  36.  
  37. # Create the table if it's not in the db
  38. conn = sqlite3.connect('social_data2.db')
  39. cur = conn.cursor()
  40. cur.execute('''CREATE TABLE IF NOT EXISTS twaccounts
  41.    (FetchDate Date, Handle Text, Category Text, Followers Integer, Description Text)
  42.    ''')
  43. conn.commit()
  44. conn.close()
  45.  
  46. #Iterate over handles and hit the API with each
  47. for handle in handles_list:
  48.     print 'Fetching @' + handle[0]
  49.     try:
  50.         user = api.GetUser(screen_name=handle[0])
  51.         followers = user.GetFollowersCount()
  52.         description = user.GetDescription()
  53.         insert_db(handle[0], handle[1], followers, description)
  54.     except:
  55.         print '-- ' + handle[0] + ' not found'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement