Skip to content

Instantly share code, notes, and snippets.

@andrealmar
Created December 6, 2016 03:36
Show Gist options
  • Select an option

  • Save andrealmar/f06e850fc388ea734cb81563b91e5a52 to your computer and use it in GitHub Desktop.

Select an option

Save andrealmar/f06e850fc388ea734cb81563b91e5a52 to your computer and use it in GitHub Desktop.
"""
This code snippet do the following:
- It grabs the last 100 tweets from 10 users
- saves the tweets in .csv format inside the CSV directory (it creates the CSV directory if it not exists)
"""
import sys, os
import csv
import tweepy
from tweepy import OAuthHandler
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_key = 'your_access_key'
access_secret = 'your_access_secret"
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#method to get a user's last 100 tweets
def get_tweets(username):
#http://tweepy.readthedocs.org/en/v3.1.0/getting_started.html#api
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#set count to however many tweets you want; twitter only allows 200 at once
number_of_tweets = 100
#get tweets
tweets = api.user_timeline(screen_name = username, count = number_of_tweets)
#create array of tweet information: username, tweet id, date/time, text
tweets_for_csv = [[username,tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in tweets]
#write to a new csv file from the array of tweets
print("writing to {0}_tweets.csv".format(username))
#creates the csv directory if not exists
if not os.path.isdir('csv'):
os.mkdir('csv')
#write the username_tweets.csv file inside the csv folder
with open("csv/{0}_tweets.csv".format(username) , 'w+') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(tweets_for_csv)
#if we're running this as a script
if __name__ == '__main__':
#FASHION and FITNESS Influencers from TWITTER (twitter ID's)
users = ['theblondesalad', 'aimeesong', 'Kayture', 'GalMeetsGlam', 'wendynguyen', 'greatist', 'dailyburn', 'FitBottomedGirl', 'bornfitness', 'TheRock']
for user in users:
get_tweets(user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment