Thursday, April 21, 2011

How to retrieve tweets from twitter

How to retrieve the most recent tweets of a twitter user without third party library. The example use the xml format provided by twitter to describe a user timeline.
import urllib
import xml.dom.minidom as minidom

def printTweets(username):
 timeline_xml = urllib.urlopen("http://twitter.com/statuses/user_timeline.xml?screen_name="+username)
 doc = minidom.parse(timeline_xml) # we're using the twitter xml format
 tweets = doc.getElementsByTagName("text") # tweet text is in ...
 
 for tweet in tweets:
  print "tweet:",tweet.childNodes[0].data,"\n"

## call the our function
printTweets("JustGlowing")
The function will print the 20 most recent JusetGlowing's tweet:
tweet: Security researchers find iPhones, 3G iPads track user location http://t.co/Fg9TIQy via @arstechnica 

tweet: White Blood Cells Solve Traveling-Salesman Problem http://zite.to/fMTv9J - RT @semanticvoid 

tweet: #IWouldTrade traffic in the city for a wonderful beach 

tweet: The time you enjoy wasting is not wasted time ~ Bertrand Russel 

tweet: numpy is a great tool, it make you feel like using matlab but you're using a free #python library #in

...

2 comments:

  1. how if we want to print more than 20 tweets?

    ReplyDelete
  2. Hi topx666,
    it's quite easy. You have to change the query string in the fifth line of code adding the parameter count:

    timeline_xml =
    urllib.urlopen("http://twitter.com/statuses/user_timeline.xml?screen_name="+username+"&count=50")

    With this line you can get 50 tweets, the maximum value that you can use is 200.

    ReplyDelete

Note: Only a member of this blog may post a comment.