Downloading Images from a Website with Java and JSoup

Oct 15, 2023 · 5 min read

In this article, we will learn how to use Java and the JSoup library to download all the images from a Wikipedia page.

—-

Overview

The goal is to extract the names, breed groups, local names, and image URLs for all dog breeds listed on this Wikipedia page. We will store the image URLs, download the images and save them to a local folder.

Here are the key steps we will cover:

  1. Import required packages
  2. Send HTTP request to fetch the Wikipedia page
  3. Parse the page HTML using JSoup
  4. Find the table with dog breed data using a CSS selector
  5. Iterate through the table rows
  6. Extract data from each column
  7. Download images and save locally
  8. Print/process extracted data

Let's go through each of these steps in detail.

Imports

We need these packages:

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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
  • Jsoup - Scrapes HTML
  • java.io - File I/O
  • java.net - Networking
  • Send HTTP Request

    To download the web page:

    String url = "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>";
    
    Document doc = Jsoup.connect(url).userAgent("Jsoup Scraper").get();
    

    Jsoup provides the connect() method to fetch and parse the page.

    Parse HTML

    The returned Document contains the parsed HTML.

    Find Breed Table

    We use a CSS selector to find the table element:

    Elements table = doc.select("table.wikitable.sortable");
    

    This selects the

    tag with the required CSS classes.

    Iterate Through Rows

    We loop through the rows like this:

    for (Element row : table.select("tr")) {
    
      // Extract data
    
    }
    

    We select all

    elements within the table.

    Extract Column Data

    Inside the loop, we extract the column data:

    Elements cells = row.select("td, th");
    
    String name = cells.get(0).select("a").text();
    String group = cells.get(1).text();
    
    String localName = cells.get(2).select("span").text();
    if(localName.equals("")) {
      localName = "";
    }
    
    String imgSrc = cells.get(3).select("img").attr("src");
    

    We use text() for text and attr() for attributes.

    Download Images

    To download and save images:

    if(!imgSrc.equals("")) {
    
      InputStream input = new URL(imgSrc).openStream();
      Files.copy(input, Paths.get("dog_images/" + name + ".jpg"), StandardCopyOption.REPLACE_EXISTING);
    
    }
    

    We open the image stream and save it to a file.

    Store Extracted Data

    We store the extracted data in lists:

    names.add(name);
    groups.add(group);
    localNames.add(localName);
    images.add(imgSrc);
    

    The lists can then be processed as needed.

    And that's it! Here is the full code:

    // Imports
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Scraper {
    
      public static void main(String[] args) throws IOException {
    
        List<String> names = new ArrayList<>();
        List<String> groups = new ArrayList<>();
        List<String> localNames = new ArrayList<>();
        List<String> images = new ArrayList<>();
    
        String url = "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>";
    
        Document doc = Jsoup.connect(url).userAgent("Jsoup Scraper").get();
    
        Elements table = doc.select("table.wikitable.sortable");
    
        for (Element row : table.select("tr")) {
    
          Elements cells = row.select("td, th");
    
          String name = cells.get(0).select("a").text();
          String group = cells.get(1).text();
    
          String localName = cells.get(2).select("span").text();
          if(localName.equals("")) {
            localName = "";
          }
    
          String imgSrc = cells.get(3).select("img").attr("src");
    
          if(!imgSrc.equals("")) {
    
            InputStream input = new URL(imgSrc).openStream();
            Files.copy(input, Paths.get("dog_images/" + name + ".jpg"), StandardCopyOption.REPLACE_EXISTING);
    
          }
    
          names.add(name);
          groups.add(group);
          localNames.add(localName);
          images.add(imgSrc);
    
        }
    
      }
    
    }
    

    This provides a complete Java solution using JSoup to scrape data and images from HTML tables. The same approach can apply to many websites.

    While these examples are great for learning, scraping production-level sites can pose challenges like CAPTCHAs, IP blocks, and bot detection. Rotating proxies and automated CAPTCHA solving can help.

    Proxies API offers a simple API for rendering pages with built-in proxy rotation, CAPTCHA solving, and evasion of IP blocks. You can fetch rendered pages in any language without configuring browsers or proxies yourself.

    This allows scraping at scale without headaches of IP blocks. Proxies API has a free tier to get started. Check out the API and sign up for an API key to supercharge your web scraping.

    With the power of Proxies API combined with Python libraries like Beautiful Soup, you can scrape data at scale without getting blocked.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: