Javascript code to get Random Image from Internet Without API - Purwana Tekno, Software Engineer
    Media Belajar membuat Software Aplikasi, Website, Game, & Multimedia untuk Pemula...

Post Top Ad

Kamis, 23 Februari 2023

Javascript code to get Random Image from Internet Without API

Without an API, it's still possible to get a random image related to data analysis by using a search engine like Google Images and programmatically scraping the search results. However, it's important to note that scraping search engines can be against their terms of service, so use this code at your own risk.


Here's an example Javascript code snippet that gets a random image related to data analysis from Google Images by scraping the search results:



const query = 'data analysis';
const safeSearch = 'active'; // set to 'off' to disable safe search

// Set up the Google Images search URL
const url = `https://www.google.com/search?q=${query}&tbm=isch&safe=${safeSearch}`;

// Fetch the HTML page from Google Images
fetch(url)
  .then(response => response.text())
  .then(html => {
    // Parse the HTML and extract the URLs of the images
    const doc = new DOMParser().parseFromString(html, 'text/html');
    const images = Array.from(doc.querySelectorAll('img')).map(img => img.src);
    
    // Get a random image URL
    const randomIndex = Math.floor(Math.random() * images.length);
    const imageUrl = images[randomIndex];
    
    // Set the image source to the URL
    const image = document.querySelector('img');
    image.src = imageUrl;
  })
  .catch(error => {
    console.error(error);
  });



Note that this code relies on web scraping, which can be unreliable and can break if Google changes their search results page layout or if they detect unusual traffic from your IP address. Also, keep in mind that web scraping can be against the terms of service of the website you're scraping from, so use this code at your own risk. 

Post Top Ad