SNIPPET
2 Upvotes

Import Tweet Data Using Twitter API & Tweepy

Python
Import and Export

An example of using Tweepy and the Twitter API to scrape tweet data. In this example the latest 500 tweets from London with the news hashtag are pulled. The location is derived from passing the coordinates of the centre of London and a 25km radius into the geocode parameter.

import tweepy
import pandas as pd

#Declare keys & tokens and open access (generate own keys using twitter developer account)
consumer_key = "XXXXXXXX"
consumer_secret = "XXXXXXXX"
access_token = "XXXXXXXXXX"
access_token_secret = "XXXXXXXXXX"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)


text_query = '#news'
count = 500

tweets = tweepy.Cursor(api.search,
                       q=text_query,
                       geocode='51.5074,-0.1278,25km',
                       result_type="recent",
                       lang="en").items(count)
fields = ['created_at', 
           'id', 
           'text',
           'location',
           'retweet_count',
           'friends_count',
           'followers_count',
           'coordinates',
           'favorite_count']

tweets_list = [[tweet.created_at, 
                 tweet.id, 
                 tweet.text,
                 tweet.user.location,
                 tweet.retweet_count,
                 tweet.user.friends_count,
                 tweet.user.followers_count,
                 tweet.coordinates,
                 tweet.favorite_count] for tweet in tweets]

tweets_df = pd.DataFrame(tweets_list,columns=fields)

By detro - Last Updated Jan. 15, 2021, 8:31 p.m.

COMMENTS
RELATED SNIPPETS
Search Snippets by Tag: