Get tweets from search
Tags: #twitter #automation #ifttt #naas_drivers #snippet

Input

Import libraries

1
import tweepy
2
import pandas as pd
Copied!

API Credentials

1
consumer_key = "XXXXXXXXXXXXXXXXXX"
2
consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Copied!

How to generate API Keys?

Model

Authentification

1
try:
2
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
3
api = tweepy.API(auth)
4
except BaseException as e:
5
print(f"Authentication has been failed due to -{str(e)}")
Copied!

Fonctions

1
def getTweets(search_words, date_since, numTweets):
2
3
# Define a pandas dataframe to store the date:
4
tweets_df = pd.DataFrame(columns = ['username', 'desc', 'location', 'following',
5
'followers', 'totaltweets', 'usercreated', 'tweetcreated',
6
'retweetcount', 'text', 'hashtags']
7
)
8
9
# Collect tweets using the Cursor object
10
# .Cursor() returns an object that you can iterate or loop over to access the data collected.
11
tweets = tweepy.Cursor(api.search, q=search_words, lang="en", since=date_since, tweet_mode='extended').items(numTweets)
12
# Store tweets into a python list
13
tweet_list = [tweet for tweet in tweets]
14
for tweet in tweet_list:
15
username = tweet.user.screen_name
16
desc = tweet.user.description
17
location = tweet.user.location
18
following = tweet.user.friends_count
19
followers = tweet.user.followers_count
20
totaltweets = tweet.user.statuses_count
21
usercreated = tweet.user.created_at
22
tweetcreated = tweet.created_at
23
retweetcount = tweet.retweet_count
24
hashtags = tweet.entities['hashtags']
25
try:
26
text = tweet.retweeted_status.full_text
27
except AttributeError:
28
text = tweet.full_text
29
30
tweet_data = [username, desc, location, following, followers, totaltweets,
31
usercreated, tweetcreated, retweetcount, text, hashtags]
32
33
tweets_df.loc[len(tweets_df)] = tweet_data
34
35
36
return tweets_df
Copied!

Initialise these function attributes:

1
search_words = "#jupyterlab OR #python OR #naas OR #naasai"
2
date_since = "2021-09-21"
3
numTweets = 50
Copied!

Output

Get the tweets

1
df = getTweets(search_words, date_since, numTweets)
Copied!
Copy link
Edit on GitHub