Monday, April 25, 2011

How to use twitter search api

The example show how to search in twitter without using third party libraries. We will use the json data-interchange format provided by twitter.
import urllib
import simplejson

def searchTweets(query):
 search = urllib.urlopen("http://search.twitter.com/search.json?q="+query)
 dict = simplejson.loads(search.read())
 for result in dict["results"]: # result is a list of dictionaries
  print "*",result["text"],"\n"

# we will search tweets about "fc liverpool" football team
searchTweets("fc+liverpool")
The program will print the most popular tweets about fc liverpool
* Poulsen set for return home? http://tinyurl.com/3vnyc9r 

* Now: Watch live press conf - Liverpool FC http://lfc.tv/GYb 

* Who wants 20 percent off a Liverpool fc stuff 

* Liverpool FC manager Gerard Houllier in Birmingham hospital after health s... http://bit.ly/glcgxJ #LFC 

* RT @darsh710: Liverpool Echo: Kenny: Alberto Aquilani welcome back at LFC after Juve loan ends http://bit.ly/emp5QZ  #LFC @ShilChandi @KaushP @BolaAnt 

* RT @empireofthekop: Liverpool Echo : News: Kenny Dalglish: Alberto Aquilani welcome back at Liverpool FC after Juventus loan ends http://bit.ly/emp5QZ #LFC #fb 

9 comments:

  1. Is there any way using this code to get more than results?

    ReplyDelete
  2. Hello Eugene,
    you can increase the number of tweets using the parameter rpp. For example, if you want 50 tweets, you have to append "&rpp=50" to the query string. You may use the function of this post calling it as follows:

    searchTweets("fc+liverpool&rpp=50")

    For more details you can visit the official documentation of the twitter API:

    https://dev.twitter.com/docs/api/1/get/search

    ReplyDelete
  3. Many thanks for quick reply - worked a treat!

    ReplyDelete
  4. Hi thanks for this but for some reason it didn't work for me except outside the def

    >>> for tweet in data['results']:
    ... print tweet['from_user_name']
    ... print tweet['text']
    ... print tweet['to_user_name']
    ... print

    any suggestions how I can load the results in excel or make it csv? I looked everywhere and it just confused me even more thanks!

    ReplyDelete
  5. you can append the resulting values into an array and save it for dumping into a file.

    ReplyDelete
  6. hi now this outdated can you give recent one

    ReplyDelete
  7. i am trying to use http://api.twitter.com/search/tweets.json?q=query but it showing bad authentication so can u suggest.

    ReplyDelete

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