lib 1002510 // jsoup

import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

static S googleImageSearch_userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
static int googleImageSearch_timeout = 10*1000;

static S googleImageSearch(S q) ctex {
  ret googleImageSearch_elementURL(googleImageSearch_query(q).first());
}

static L<S> googleImageSearch_multi(S q) ctex {
  ret map(f googleImageSearch_elementURL, googleImageSearch_query(q));
}

static S googleImageSearch_elementURL(Element media) ctex {
  ret htmldecode(media.attr("abs:data-src")); 
}

static Elements googleImageSearch_query(S q) ctex {
  ret googleImageSearch_loadPage(q).select("[data-src]");
}

static Document googleImageSearch_loadPage(S q) ctex {
  S googleUrl = "https://www.google.com/search?tbm=isch&q=" + urlencode(q);
  print("Googling " + quote(q));
  ret Jsoup.connect(googleUrl).userAgent(googleImageSearch_userAgent).timeout(googleImageSearch_timeout).get();
}