m2skills

get tweets with hashtags

Oct 13th, 2017
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # program to download tweets by hashtags
  2. import time
  3. import json
  4.  
  5. # http://www.tweepy.org/ or pip install tweepy
  6.  
  7. from tweepy import Stream
  8. from tweepy import OAuthHandler
  9. from tweepy.streaming import StreamListener
  10.  
  11. # Get your Twitter API credentials and enter them here
  12. consumer_key = ''
  13. consumer_secret = ''
  14. access_key = ''
  15. access_secret = ''
  16.  
  17. # Counter indicated numver of tweets downloaded
  18. Counter = 0
  19. class listener(StreamListener):
  20.  
  21.     def on_data(self,data):
  22.         global Counter
  23.        
  24.         # parsing the tweets and writing it to csv file \
  25.         # for the program we have stored only 5 fields but you can add more
  26.         with open('DataDL2.csv','a') as tf:
  27.             temp = json.loads(data)
  28.             user = temp["user"]        
  29.             output_string = "{0}, {1}, {2}, {3}, {4}".format(temp["text"], user["screen_name"], user["favourites_count"], temp["created_at"], temp["retweeted"])
  30.             tf.write(output_string + "\n")
  31.             Counter += 1
  32.             if Counter % 5 == 0:       
  33.                 print(Counter)
  34.         return True
  35.  
  36.     def on_error(self,status):
  37.         print(status)
  38.         print("ON ERROR")
  39.  
  40.  
  41. while True:    
  42.     try:                   
  43.         auth =OAuthHandler(ckey,csecret)
  44.         auth.set_access_token(atoken,asecret)
  45.         print("Data collection started : ")
  46.         twitterStream = Stream(auth,listener())
  47.        
  48.         # keywords to track in tweets
  49.         # add your own keywords in the below list
  50.         twitterStream.filter(track = ['#apple', '#google', '#samsung', '#sony' ])
  51.  
  52.     except Exception:      
  53.         pass
Add Comment
Please, Sign In to add comment