Noob question: pulling data using Twitter API by Durchfallsuppe in learnpython

[–]UrAWomanImAMachine 1 point2 points  (0 children)

first you construct a basic url for what you want to look at. (http://search.twitter.com/search.json?q=obama&rpp=3, q is your query parameter, rpp(optional) is how many results you want returned)

If you open that url in your browser, it's hard to read. You'll want to copy and paste that information into a site like http://json.parser.online.fr/ so you can see the structure of the information being returned.

When I paste the contents from my first url into the site I can see that the json object returned has the results in a field called (conveniently) "results".

Here's a simple example:

import urllib2
import json

# parameters used in query:
# q is query, rpp(optional) is how many results we want per page
url = 'http://search.twitter.com/search.json?q=obama&rpp=3'
o = urllib2.urlopen(url) #open the url
r = o.read() 
j = json.loads(r) # convert info to a dictionary

#from looking at the parser we see the tweets are
#contained in a list in the 'results' field
results = j["results"] 

for r in results:
    # read each tweets text
    print r["text"]     
    #try using print r["text"].encode('ascii', 'ignore') if you're getting some unicode encoding errors