Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script for "Google search by image"

I have checked Google Search API's and it seems that they have not released any API for searching "Images". So, I was wondering if there exists a python script/library through which I can automate the "search by image feature".

like image 413
AKG Avatar asked Dec 02 '11 20:12

AKG


People also ask

How do I use Google image Search in Python?

from google_images_search import GoogleImagesSearch gis = GoogleImagesSearch('your_dev_api_key', 'your_project_cx') _search_params = { 'q': '...', 'num': 123, } # get first 123 images: gis.search(search_params=_search_params) # take next 123 images from Google images search: gis. next_page() for image in gis.

How do you make a search engine like Google in Python?

Create a file urls.py in the engine folder. Append the following lines. Our project is now done , to fire it up type python3 manage.py runserver enter this url in your browser and you should see this. Now enter your query in the search bar and your should get your results like this.


2 Answers

There is no API available but you are can parse the page and imitate the browser, but I don't know how much data you need to parse because google may limit or block access.

You can imitate the browser by simply using urllib and setting correct headers, but if you think parsing complex web-pages may be difficult from python, you can directly use a headless browser like phontomjs, inside a browser it is trivial to get correct elements using javascript/DOM

Note before trying all this check google's TOS

like image 170
Anurag Uniyal Avatar answered Oct 24 '22 13:10

Anurag Uniyal


This was annoying enough to figure out that I thought I'd throw a comment on the first python-related stackoverflow result for "script google image search". The most annoying part of all this is setting up your proper application and custom search engine (CSE) in Google's web UI, but once you have your api key and CSE, define them in your environment and do something like:

#!/usr/bin/env python

# save top 10 google image search results to current directory
# https://developers.google.com/custom-search/json-api/v1/using_rest

import requests
import os
import sys
import re
import shutil

url = 'https://www.googleapis.com/customsearch/v1?key={}&cx={}&searchType=image&q={}'
apiKey = os.environ['GOOGLE_IMAGE_APIKEY']
cx = os.environ['GOOGLE_CSE_ID']
q = sys.argv[1]

i = 1
for result in requests.get(url.format(apiKey, cx, q)).json()['items']:
  link = result['link']
  image = requests.get(link, stream=True)
  if image.status_code == 200:
    m = re.search(r'[^\.]+$', link)
    filename = './{}-{}.{}'.format(q, i, m.group())
    with open(filename, 'wb') as f:
      image.raw.decode_content = True
      shutil.copyfileobj(image.raw, f)
    i += 1
like image 21
user2926055 Avatar answered Oct 24 '22 12:10

user2926055