Skip to content

Instantly share code, notes, and snippets.

@anku255
Created February 6, 2017 14:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anku255/0cebd75cce675f2b56de1ef48ec06575 to your computer and use it in GitHub Desktop.
Save anku255/0cebd75cce675f2b56de1ef48ec06575 to your computer and use it in GitHub Desktop.
Code Snippet to scrape tweets into a csv file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import csv
#http://www.tweepy.org/
import tweepy
#Get your Twitter API credentials and enter them here
consumer_key = "Paste your consumer key here"
consumer_secret = "paste your consumer secret here"
access_key = "paste your access key here"
access_secret = "paste your access secret here"
#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 = 10
#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 = [[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))
with open("{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__':
#get input for username
Username = input("Enter the Twitter Username: ")
get_tweets(Username)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment