Python ProgrammingPython Programming

How to extract twitter data using Twitter API?

Twitter has an enormous amount of tweets every day, and every tweet has some information which social media marketers using for their analysis.

tweepy is required library for this recipe. Installing tweepy on your computer is a very simple. You simply need to install it using pip.

pip install tweepy

Tweeter Data Collection for Analysis

import tweepy
from tweepy import OAuthHandler

# Your Twittter App Credentials
consumer_key = "XXXXXXXXXXX"
consumer_secret = "YYYYYYYYYYY"
access_token = "ZZZZZZZZZZZZZZZZZZ"
access_token_secret = "CCCCCCCCCCCCCCCCCC"

# Calling API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# Provide the keyword you want to pull the data e.g. "Python".
keyword = "Python"

# Fetching tweets
tweets = api.search(keyword, count=10, lang='en', exclude='retweets',
                    tweet_mode='extended')

for item in tweets:
    print(item)

The consumer key, consumer secret, access token and access token secret you can get from Twitter developer portal after login and create your app. The above program on execution pull the top 10 tweets with the keyword Python is searched. The API will pull English tweets since the language given is "en" and it will exclude retweets.