Sylvatica.

Back to Library

Google Image

js 1/27/2026
15
const axios = require("axios")
const cheerio = require("cheerio")
const queryString = require("querystring")

const baseURL = "https://www.google.com/search?"
const imageExt = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"]

function hasImageExt(s) {
  s = s.toLowerCase()
  return imageExt.some(e => s.includes(e))
}

function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[arr[i], arr[j]] = [arr[j], arr[i]]
  }
  return arr
}

async function googleImage(query) {
  const url =
    baseURL +
    queryString.stringify({
      tbm: "isch",
      q: query,
      hl: "en"
    })

  const { data } = await axios.get(url, {
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36"
    },
    timeout: 30000
  })

  const $ = cheerio.load(data)
  const scripts = $("script")
  let images = []

  scripts.each((_, el) => {
    const text = $(el).html()
    if (!text || !hasImageExt(text)) return

    const regex = /(https?:\/\/[^"]+\.(?:jpg|jpeg|png|gif|bmp|webp)[^"]*)/gi
    let m
    while ((m = regex.exec(text)) !== null) {
      let img = m[1]
        .replace(/\\u003d/g, "=")
        .replace(/\\u0026/g, "&")
        .replace(/\\\//g, "/")
        .replace(/\\/g, "")

      if (
        img.startsWith("http") &&
        !img.includes("gstatic.com") &&
        img.length > 20
      ) {
        images.push(img)
      }
    }
  })

  images = [...new Set(images)]
  if (!images.length) throw new Error("No image found")

  shuffle(images)

  return images[Math.floor(Math.random() * images.length)]
}

module.exports = { googleImage }