Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Wednesday, May 11, 2011

How to download the profile picture of a facebook user

The follwing function uses the facebook graph API to retrieve the url of the profile picture from the user's id:
import urllib
import simplejson

def getProfilePicUrl(user_id):
 api_query = urllib.urlopen('https://graph.facebook.com/'+user_id)
 dict = simplejson.loads(api_query.read())
 return dict['picture']

When we visit a facebook profile the user id is displayed in the address of the page. This is the address of the cocacola page, in red the user id of coca cola:

http://www.facebook.com/profile.php?id=40796308305

now can use the id to save the profile picture of coca cola.

pic_url = getProfilePicUrl('40796308305')
pic = urllib.urlopen(pic_url) # retrieve the picture
f = open("cocacola.jpg","wb")
f.write(pic.read()) # save the pic
f.close()
The script will save the picture on the disk.

Warning: coca cola has a public profile, non-public profile need authentication.

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