Collect Tweets from the Twitter API Using Python

No comments
Many of you have asked how to retrieve tweets from the Twitter API using Python. Well... it's extremely simple! First of all, if you still don't have one, you have to open a Twitter developer account and obtain your "secrets" (as explained here: https://dev.twitter.com/discussions/631) that you will later use to authenticate.

The only external libraries that you will need are "requests" (get it here: http://docs.python-requests.org/en/latest) that makes simpler to interact with the API and requests_oauthlib (get it here: https://github.com/requests/requests-oauthlib) to simplify the authorization process. Once you have installed it you can create an authorization variable using this simple code:

 oauth = OAuth1(CONSUMER_KEY,  
         client_secret=CONSUMER_SECRET,  
         resource_owner_key=OAUTH_TOKEN,  
         resource_owner_secret=OAUTH_TOKEN_SECRET)  

The four parameters are the "secrets" that you obtained when you created your Twitter developer account.
We are almost done! You just need to make a request to the Twitter API using the authorization variable previously created:

 r = requests.get(url="https://api.twitter.com/1.1/search/tweets.json?q=Obama", auth=oauth)  

For example in this case we retrieved the most recent tweets talking about Obama.
To have a look at the content of the retrieved tweets you can just print it:

 print r.json()  

or save the content to a csv file using the python csv module.

I hope that everything was clear, feel free to comment if you need more help!

No comments :

Post a Comment