I want to collect tweets (in python dictionary format) containing some key words into a csv file. I have used tweepy cursor. But it returns nothing.
Following the answer in "Managing Tweepy API Search" I have tried to collect tweets using cursor. But the code stops after some seconds, with out returning any message.
import TwitterCredentials
import tweepy
import csv
from tweepy import OAuthHandler
import json
def authenticate():
auth=OAuthHandler(TwitterCredentials.consumerKey,
TwitterCredentials.consumerSecretKey)
auth.set_access_token(TwitterCredentials.accessToken,
TwitterCredentials.accessTokenSecret)
api=tweepy.API(auth)
return api
def collectTweet(api, query, max_tweets):
i=1
for tweet in tweepy.Cursor(api.search, q=query).items(max_tweets):
loadCsvFile(json.loads(tweet))
print(str(i)+ " ")
i+=1
def loadCsvFile(tweet):
csv_file.writerow([tweet['id'],tweet['created_at'],tweet['text'],
tweet['retweet_count'],tweet['source']])
if __name__ == '__main__':
query=['air pollution', 'PM 2.5']
max_tweets=500
f=open('collected_tweets.csv', 'w')
csv_file=csv.writer(f)
csv_file.writerow(['id','created_at','text',
'retweet_count','source'])
api=authenticate()
collectTweet(api, query, max_tweets)
I want to get the messages in dictionary format such that the id, created_at, text, source information can be extracted from it.
This code didn't return any error and didn't return any message also.
the tweepy.cursor returns status where _json is the dict where all the field of a tweet are present. so the code should be
for status in tweepy.Cursor(api.search, q=query, lang='en').items(max_tweets):
loadCsvFile(status._json)
... Then it worked.