Python to download all tweets from Twitter

import urllib2
username = ''
password = ''
format = 'json' # json or xml
filename = 'archive.json' # filename of the archive
tweets = 164 # number of tweets
pages = (int(float(tweets)/float(80)))+1
auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth.add_password(None, 'http://twitter.com/account/', username, password)
authHandler = urllib2.HTTPBasicAuthHandler(auth)
opener = urllib2.build_opener(authHandler)
urllib2.install_opener(opener)
i = 1
response = ''
print 'Downloading tweets. Note that this may take some time'
while i <= pages:
    request = urllib2.Request('http://twitter.com/account/archive.' 
    + format + '?page=' + str(i))
    response = response + urllib2.urlopen(request).read()
    i = i + 1
handle = open(filename,"w")
handle.write(response)
handle.close()
print 'Archived ' + str(tweets) + ' of ' + username + 
''s tweets to ' + filename
This entry was posted in Python. Bookmark the permalink.

Comments are closed.