Last active
November 11, 2015 10:59
-
-
Save revox/6c65a0940c284106f71f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import twitter | |
import json | |
import csv | |
# == OAuth Authentication == | |
# The consumer keys can be found on your application's Details | |
# page located at https://dev.twitter.com/apps ("Keys and Access tokens" tab) | |
consumer_key="" | |
consumer_secret="" | |
# Create an access token under the the "Your access token" section | |
access_token="" | |
access_token_secret="" | |
auth = twitter.oauth.OAuth(access_token, access_token_secret,consumer_key, consumer_secret) | |
twitter_api = twitter.Twitter(auth=auth) | |
# WARNING you will only be able to ask for trends using this code 15 timesin 15 minutes otherwiese you will be RATE LMITED | |
# https://dev.twitter.com/rest/public/rate-limits | |
# The Yahoo! Where On Earth ID for the entire world is 1. | |
# See https://dev.twitter.com/docs/api/1.1/get/trends/place and | |
# http://developer.yahoo.com/geo/geoplanet/ | |
# Get codes at http://woeid.rosselliot.co.nz/ | |
SWEDEN_WOE_ID = 23424954 | |
# Prefix ID with the underscore for query string parameterization. | |
# Without the underscore, the twitter package appends the ID value | |
# to the URL itself as a special case keyword argument. | |
sweden_trends = twitter_api.trends.place(_id=SWEDEN_WOE_ID) | |
# print in a readable format to the console, this is important as | |
# it allows us to see the hierachy of the object and so we can drill down into | |
# the object to get the values we want | |
print json.dumps(sweden_trends, indent=1) | |
# BY looking at the printout above we can see that Twitter returns a list (it starts with a square bracket) | |
# and in that list is an object that has two keys, the first the date which has a date value, the second is | |
# another list called trends, each item in the list is an object with four key/value pairs in it describing each | |
# trend, in this case we just want the name and the link to the trend | |
# So lets dig out the list of trends fist to make the following code that gets the two desried avlues from each trend sinpler | |
trends = sweden_trends[0]['trends'] | |
# open a file for writing to | |
csvfile = open('sweden_trends.csv', 'w') | |
# point a CSV writer at the file | |
csvwriter = csv.writer(csvfile) | |
# now loop over the items in the trends list and write the name and URL to file | |
for trend in trends: | |
csvwriter.writerow([trend['name'],trend['url']]) | |
print "done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment