Downloading profile pictures using the Google+ API
Now that we have established how to use the Google+ API, we can design a script to pull down pictures. The aim here is to put faces to names taken from web pages. We will send a request to the API through a URL, handle the response through JSON, and create picture files in the working directory of the script.
How to do it
Here's a simple script to download profile pictures using the Google+ API:
import urllib2 import json GOOGLE_API_KEY = "{Insert your Google API key}" target = "packtpub.com" api_response = urllib2.urlopen("https://www.googleapis.com/plus/v1/people? query="+target+"&key="+GOOGLE_API_KEY).read() json_response = json.loads(api_response) for result in json_response['items']: name = result['displayName'] print name image = result['image']['url'].split('?')[0] f = open(name+'.jpg','wb+') f.write(urllib2.urlopen(image).read()) f.close()
How it works
The first change is to store the display name into a variable, as this is then reused later on:
name = result['displayName'] print name
Next, we grab the image URL from the JSON response:
image = result['image']['url'].split('?')[0]
The final part of the code does a number of things in three simple lines: firstly it opens a file on the local disk, with the filename set to the name
variable. The wb+
flag here indicates to the OS that it should create the file if it doesn't exist and to write the data in a raw binary format. The second line makes a HTTP GET
request to the image URL (stored in the image
variable) and writes the response into the file. Finally, the file is closed to free system memory used to store the file contents:
f = open(name+'.jpg','wb+') f.write(urllib2.urlopen(image).read()) f.close()
After the script is run, the console output will be the same as before, with the display names shown. However, your local directory will now also contain all the profile images, saved as JPEG files.