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(""+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
The function will print the 20 most recent JusetGlowing's tweet:
tweet: Security researchers find iPhones, 3G iPads track user location via @arstechnica 

tweet: White Blood Cells Solve Traveling-Salesman Problem - 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



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

  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 =

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