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: that you will later use to authenticate.

The only external libraries that you will need are "requests" (get it here: that makes simpler to interact with the API and requests_oauthlib (get it here: to simplify the authorization process. Once you have installed it you can create an authorization variable using this simple code:

 oauth = OAuth1(CONSUMER_KEY,  

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="", 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