Get Trending Hashtags From Twitter
Authenticate with the Twitter API. Get your keys at https://apps.twitter.com.
import tweepy
consumer_key = 'XXXX'
consumer_secret = 'XXXX'
access_key = 'XXXX'
access_secret = 'XXXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
Now to get those pesky trending hashtags. We have to supply a location in the form of a Where On Earth Identifier (WOEID). You can look these up at http://woeid.rosselliot.co.nz. I've chosen the United Kingdom.
for location in api.trends_place('23424975'):
for trend in location['trends']:
trend = trend['name']
print(trend)
That'll spew out all the trending topics and hashtags. We only want the hashtags so we'll change our code like so...
for location in api.trends_place('23424975'):
for trend in location['trends']:
trend = trend['name']
if trend.startswith('#'):
print(trend)
That's better. I'm only interested in using 2 of them, in a single string, so we'll wrap all this up into a function and have it return a given amount.
from random import sample
def get_trending(amount):
trending = []
for location in api.trends_place('23424975'):
for trend in location['trends']:
trend = trend['name']
if trend.startswith('#'):
trending.append(trend)
return sample(trending, amount)
hashtags = ' '.join(get_trending(2))
print(hashtags)
Thanks for reading. x
Resources
- Python: https://python.org
- Tweepy: https://tweepy.readthedocs.io/en/latest