How to Get Trending Hashtags on Twitter in 2022 With Python

Created on Jan 24, 2022

We discussed before how to get trending topics on Twitter in Python using the Tweepy API wrapper.

Today, let’s discuss how to get trending hashtags in a specific country and get a list of those tweets in a specific language. The code is customized so that you can change the country to whatever you want. The snippet code is hosted on gist and you can find it at the end of this post.

Let’s dive in and start with the athentication and authorization part. If you missed out on what the difference is, please revise the previous post .

To create the Tweepy api object, you need to import the tweepy library and use the keys and tokens that you get from the Twitter Developer:

import tweepy

def get_api(**kwargs):
    auth = tweepy.OAuthHandler(kwargs["api_key"], kwargs["api_key_secret"])
    auth.set_access_token(
        kwargs["access_token"],
        kwargs["access_token_secret"]
        )
    return tweepy.API(auth)

and the driver code would be:

import os

if __name__ == "__main__":
    api = get_api(
        api_key=os.getenv("API_KEY"),
        api_key_secret=os.getenv("API_KEY_SECRET"),
        access_token=os.getenv("ACCESS_TOKEN"),
        access_token_secret=os.getenv("ACCESS_TOKEN_SECRET")
    )

Now, we have the api object ready. Let’s get the trending search results for a specific country:

import geocoder

def get_trends(api, loc):
    # Object that has location's latitude and longitude.
    g = geocoder.osm(loc)

    closest_loc = api.closest_trends(g.lat, g.lng)
    trends = api.get_place_trends(closest_loc[0]["woeid"])
    return trends[0]["trends"]

To test that, let’s append that snippet to the driver code and dump the trends to the console:

import json

if __name__ == "__main__":
    loc = "Egypt"
    trends = get_trends(api, loc)
    print(json.dumps(trends, indent=4))

You can change loc to any country you want and explore what tweets are trending there.

As you might know, not all trending search results are hashtags. Rather, some of them are particularly starting with the # symbol. Let’s filter out the hashtags and get the list of those hashtags with the following function:

def extract_hashtags(trends):
    hashtags = [trend["name"] for trend in trends if "#" in trend["name"]]
    return hashtags

To test that:

if __name__ == "__main__":
    hashtags = extract_hashtags(trends)
    for hashtag in hashtags:
        print(hashtag)

Now, you can see the list of hashtags that are trending in the country you chose.

Pick a hashtag from that list. Let’s see the first one and let’s see how to get the tweets for that hashtag:

def get_n_tweets(api, hashtag, n, lang=None):
    for status in tweepy.Cursor(
        api.search_tweets,
        q=hashtag,
        lang=lang
    ).items(n):
        print(f"https://twitter.com/i/web/status/{status.id}")

This function get_n_tweets() will get n tweets for a particular hashtag. It uses the tweepy.Cursor object to iterate over each status. To pick a specific hashtag and call that function, use:

if __name__ == "__main__":
    hashtag = hashtags[0]
    status = get_n_tweets(api, hashtag, 5, "ar")

This will get you the first 5 tweets for the first hashtag in the Tweepy response.

Let’s put it all together with the code below:

Resources