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.

4 comments:

  1. It's a bit old?

    Now it's easier obtain the image writing /piture at the end of the object:

    http://graph.facebook.com/cocacola/picture

    At the documentation explains how to obtain the different picture sizes.
    https://developers.facebook.com/docs/reference/api/using-pictures/

    ReplyDelete
  2. How can you put a picture of your self on facebook profile picture page?

    ReplyDelete
  3. can u tell me how to download non-public photos. i have the access token.

    ReplyDelete
  4. how to run this code?

    ReplyDelete

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