Almoullim
7/11/2016 - 4:29 AM

Get Twitter followers, following, and tweets count using Python and YQL

Get Twitter followers, following, and tweets count using Python and YQL

# Made for Python v3.x 
# Hacked together by Ali Almoullim.

'''
Get your Twitter profile
following, followers, and tweets count
using Python and Yahoo Query Language (YQL).
'''

#Use `pip3 install requests` to install the module.
import requests

# Your twitter username.
twitterUsername = 'alialmoullim'

# Set twitterUrl to twitter.com and append the username to it.
twitterUrl = 'https://twitter.com/' + twitterUsername
# Set yql to YQL query url.
yql = 'http://query.yahooapis.com/v1/public/yql?q='
# set the xpath value to select the followers, following,
# and tweets html elements to get their contents.
xpath = "//li/a/span[contains(@class,'ProfileNav-value')]"
# Set query to YQL query to collect the information from twitter.
query = '''select content from html where
    url=\"''' + twitterUrl + '\" and xpath=\"' + xpath + '\" limit 3'
# Finally preform the requests to to get 
res = requests.get(yql + query, params=dict(format='json')).json()

'''
The information is collected as a json format like
dictionaries and lists.
The query dict contains information about the YQL query,
the results key contains a another dict of the results form the query,
and the span key contains a list with the info selected using the query,
the first [0] is the tweets count, the second is the
following count, and the third is the followers count
'''

tweets = res['query']['results']['span'][0]
following = res['query']['results']['span'][1]
followers = res['query']['results']['span'][2]

print('Followers: ', followers)
print('Following: ', following)
print('Tweets: ', tweets)