Finding Images on Shutterstock

Recently, on this here pointless blog, I wanted to make a website which could generate random names, and I got a quick start based on a great word list. The next functionality that I wanted to add was the ability to display an image based on the search term.

Unfortunately, finding a method to grab a random image off of the internet based on a search term is a little trickier than I originally imagined. My goal was to simply find a coded url for a site, and then grab an image based off the search terms. Navigating the DOM for several search engines required more than simple cheerio navigation, but I eventually found that Shutterstock returned html which was easy to parse.

After a little experimentation and some replacement via regex, I managed to get the top image search result. The url is given by the following string http://www.shutterstock.com/cat.mhtml?&searchterm="+word1+"+"+word2+"&media_type=images, and the final code for retrieving and displaying the image is as follows:

app.get('/', function (req, res) {
   var pichtml = "<img src=\"";

   request(url, function (error, response, body) {
     if (!error) {
     // load a page into cheerio
     // grab the entire body.
     var $page = cheerio.load(body);
     text = $page(".gc_clip").html();

     text = text.replace(/.*<img src="/,"");
     text = text.replace(/".*/,"");
     pichtml = pichtml + text;
     console.log(text)
     } else {
        return "We’ve encountered an error: " + error;
     }
   pichtml = pichtml + "\">";
   res.send(pichtml);
});

The next plan for this little application is to build a module which can respond to each click and then deploy it to the world!