Downloading Images from a Website with Go and goquery

Oct 15, 2023 · 4 min read

In this article, we will learn how to use Go and the goquery 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 goquery
  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 (
  "net/http"
  "github.com/PuerkitoBio/goquery"
  "os"
)
  • net/http - Sends HTTP requests
  • goquery - Scrapes HTML/XML
  • os - Provides OS functionality
  • Send HTTP Request

    To download the web page:

    url := "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>"
    
    client := &http.Client{}
    req, _ := http.NewRequest("GET", url, nil)
    
    req.Header.Set("User-Agent", "Mozilla/5.0")
    
    resp, _ := client.Do(req)
    
    defer resp.Body.Close()
    

    We make a GET request and set a custom user-agent header.

    Parse HTML

    To parse the HTML:

    doc, _ := goquery.NewDocumentFromReader(resp.Body)
    

    The goquery document represents parsed HTML/XML.

    Find Breed Table

    We use a CSS selector to find the table element:

    table := doc.Find("table.wikitable.sortable")
    

    This selects the

    tag with the required CSS classes.

    Iterate Through Rows

    We loop through the rows:

    table.Find("tr").Each(func(i int, s *goquery.Selection) {
    
      // Extract data
    
    })
    

    We iterate through each

    element within the table.

    Extract Column Data

    Inside the loop, we extract the column data:

    cells := s.Find("td, th")
    
    name := cells.Eq(0).Find("a").Text()
    group := cells.Eq(1).Text()
    
    localName := cells.Eq(2).Find("span").Text()
    if localName == "" {
      localName = ""
    }
    
    img := cells.Eq(3).Find("img")
    photograph, _ := img.Attr("src")
    

    We use Text() for text and Attr() for attributes.

    Download Images

    To download and save images:

    if photograph != "" {
    
      response, _ := http.Get(photograph)
      defer response.Body.Close()
    
      f, _ := os.Create("dog_images/" + name + ".jpg")
      defer f.Close()
    
      io.Copy(f, response.Body)
    
    }
    

    We make a new GET request for the image and save it to a file.

    Store Extracted Data

    We store the extracted data:

    names = append(names, name)
    groups = append(groups, group)
    localNames = append(localNames, localName)
    photographs = append(photographs, photograph)
    

    The slices can then be processed as needed.

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

    // Imports
    import (
      "net/http"
      "github.com/PuerkitoBio/goquery"
      "os"
      "io"
    )
    
    // Slices to store data
    var names []string
    var groups []string
    var localNames []string
    var photographs []string
    
    // HTTP request
    url := "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>"
    
    client := &http.Client{}
    req, _ := http.NewRequest("GET", url, nil)
    
    req.Header.Set("User-Agent", "Mozilla/5.0")
    
    resp, _ := client.Do(req)
    
    defer resp.Body.Close()
    
    // Load HTML
    doc, _ := goquery.NewDocumentFromReader(resp.Body)
    
    // Find table
    table := doc.Find("table.wikitable.sortable")
    
    // Iterate rows
    table.Find("tr").Each(func(i int, s *goquery.Selection) {
    
      // Get cells
      cells := s.Find("td, th")
    
      // Extract data
      name := cells.Eq(0).Find("a").Text()
      group := cells.Eq(1).Text()
    
      localName := cells.Eq(2).Find("span").Text()
      if localName == "" {
        localName = ""
      }
    
      img := cells.Eq(3).Find("img")
      photograph, _ := img.Attr("src")
    
      // Download image
      if photograph != "" {
    
        response, _ := http.Get(photograph)
        defer response.Body.Close()
    
        f, _ := os.Create("dog_images/" + name + ".jpg")
        defer f.Close()
    
        io.Copy(f, response.Body)
    
      }
    
      // Store data
      names = append(names, name)
      groups = append(groups, group)
      localNames = append(localName, localName)
      photographs = append(photographs, photograph)
    
    })
    

    This provides a complete Go solution using goquery 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: