Extracting Images from Websites
Overview
Welcome to the lesson on extracting and saving images from web pages. In this lesson, you will learn how to use JavaScript with the Cheerio and Axios libraries to scrape images from web pages and save them locally. By the end of this lesson, you will have a solid understanding of the entire process, from making web requests to locating image elements and saving the images.
Making Web Requests and Parsing HTML
We start by fetching the HTML content of the website we want to scrape. In this case, we'll use https://books.toscrape.com/.
First, import the necessary libraries, make an HTTP GET request to the website, and parse the HTML content using Cheerio.
In this example, we fetch and parse the HTML content of the Books website.
Locating and Extracting Image URLs
With the parsed HTML content, use Cheerio to locate image elements and extract their URLs from the src attribute:
We now have a list of image URLs extracted from the web page.
Downloading and Saving Images
Finally, we will download and save the extracted images to the local file system.
Let's first ensure the images directory exists and create it if it doesn't, using the fs module:
Next, we can iterate over the image URLs, send requests to each URL, and save the images:
After running the code, all the images will be saved in the images directory. Let's understand the code step by step:
- We iterate over the image URLs extracted from the web page. Note that we construct the full URL by prepending the base URL if the image URL is relative.
- For each URL, we send an HTTP GET request to download the image using Axios with
responseType: 'stream'for efficient handling of binary data. - If the request is successful (status code
200), we extract the image name from the URL and create a write stream to save the image to theimagesdirectory. We use thepipe()method to efficiently transfer data from the response stream to the file. - We wait for the write operation to complete using a Promise that resolves when the stream finishes writing.
- Finally, we print a message indicating that the image was saved or log any errors that occurred during the download process.
Summary and Exercises
In this lesson, you learned how to extract and save images from web pages using JavaScript with the Cheerio and Axios libraries. You learned how to make web requests, parse HTML content, locate image elements, extract image URLs, and save images to the local file system.
Now it's time to practice what you've learned in the exercises. Good luck!
