Skip to content

Instantly share code, notes, and snippets.

@elsehow
Last active December 15, 2017 08:48
Show Gist options
  • Save elsehow/ef1269b79ee5e20bda8a1d9c3c8eaa86 to your computer and use it in GitHub Desktop.
Save elsehow/ef1269b79ee5e20bda8a1d9c3c8eaa86 to your computer and use it in GitHub Desktop.
Google image search in Python3
# setup a custom search http://www.google.com/cse/manage/all
# you can set up wildcards like *.com, *.org, *.net etc to cast a broad net for your custom search
# remmeber to flip the "images" switch if you want that service
from googleapiclient.discovery import build
def image_search (query):
service = build("customsearch", "v1",
developerKey="[YOUR API KEY - console.developers.google.com]")
res = service.cse().list(
q=query, #'lectures',
cx='[your custom search ID - go to http://www.google.com/cse/manage/all to find your cx',
searchType='image',
rights='cc_publicdomain cc_attribute cc_sharealike cc_noncommercial cc_nonderived',
).execute()
urls = [item['link'] for item in res['items']]
return urls
img_urls = image_search('lectures')
# we can download and open an image
from io import BytesIO
import requests
from PIL import Image
def load_image (url):
bytes = requests.get(url).content
file = BytesIO(bytes)
return Image.open(file)
img = img_urls[0]
load_image(img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment