1
votes

My goal is to have a Google docs spreadsheet of keywords that I can loop through, perform an image search for each keyword, and save the resulting image URL's in the same spreadsheet.

There's a whole Google image search javascript API found here. Within Google Sheets the custom apps script also uses javascript. I'm looking for a way to access this image search API using apps script for a google doc but can't seem to find a way to import the library.

Update: non-deprecated google search API link: here

2

2 Answers

2
votes

Unfortunately, Google deprecated the API you linked to. Also, there does not appear to be a similar API available in Google Apps Script. Therefore, you have one choice left, and that is to construct the URL to Google's image search and use the URL fetch app to grab the HTML. From that, you might be able to find links to the images that were returned, but be forewarned, even if you do get it working, Google hates anything that uses its search like a bot and will likely flag the traffic. Sorry if this is not the answer you wanted, but it is the only answer there is.

3
votes

Taking the advice from above I abandoned trying to incorporate the google search API directly and instead used the URL approach. Here's what I ended up with in case anyone wants to do this in the future.

var delayMilli = 0;

function fetchURL(sheet,row,urlCell) {
  delay(delayMilli)
  var row = sheet.getRange(row,1,1,2).getValues()[0];
  // This example searches for two terms located in row number "row"
  var response = UrlFetchApp.fetch("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="+row[1]+"%20"+row[0]);
  var data = JSON.parse(response);
  if (data.responseData.results[0]) {
    var urlString = data.responseData.results[0].url;
    urlCell.setValue(urlString);
    if (delayMilli >= 0) {
      delayMilli -= 5; 
    }
  } else {
    // Delay the method and try again.
    delayMilli += 100;
    fetchURL(sheet,row,urlCell)
  } 
}

If the response object is empty it's usually because Google has rejected the server call. In the above code, each failed iteration will add 0.1 seconds to the delay time before trying again. Once the calls start going through again without any issues the delay time is slowly reduced back to 0. Seemed to work pretty well for me.

One big drawback is you can't filter your results by image size, restriction level, etc.