Downloading Images from a Website with R and rvest

Oct 15, 2023 · 4 min read

In this article, we will learn how to use R and the rvest package 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. Load required packages
  2. Send HTTP request to fetch the Wikipedia page
  3. Parse the page HTML using rvest
  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.

Packages

We need these packages:

library(rvest)
library(xml2)
  • rvest - Scrapes HTML pages
  • xml2 - Parses XML/HTML
  • Send HTTP Request

    To download the web page:

    url <- "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>"
    
    page <- rvest::read_html(url)
    

    rvest provides the read_html() function to fetch the page.

    Parse HTML

    The returned page object contains parsed HTML.

    Find Breed Table

    We use a CSS selector to find the table element:

    table <- page %>% html_nodes("table.wikitable.sortable")
    

    This selects the

    tag with the required CSS classes.

    Iterate Through Rows

    We loop through the rows like this:

    table %>%
      html_nodes("tr") %>%
      .[. != 1] %>%
      html_nodes("td, th") %>%
      {
    
        # Extract data
    
      }
    

    We filter to skip the header row.

    Extract Column Data

    Inside the loop, we extract the column data:

    name <- html_text(.[[1]])
    group <- html_text(.[[2]])
    
    local_name <- html_text(.[[3]])
    if(local_name == ""){
      local_name <- NA
    }
    
    img_url <- xml_attr(.[[4]], "src")
    

    We use html_text() and xml_attr() to extract elements.

    Download Images

    To download and save images:

    if(!is.na(img_url)){
    
      img <- GET(img_url)
      writeBin(img, paste0("dog_images/",name,".jpg"))
    
    }
    

    We use the GET() function to download the image and write it to a file.

    Store Extracted Data

    We store the extracted data in vectors:

    names <- c(names, name)
    groups <- c(groups, group)
    local_names <- c(local_names, local_name)
    photos <- c(photos, img_url)
    

    The vectors can then be processed as needed.

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

    # Load packages
    library(rvest)
    library(xml2)
    
    # Vectors to store data
    names <- character()
    groups <- character()
    local_names <- character()
    photos <- character()
    
    # Fetch HTML
    url <- "<https://commons.wikimedia.org/wiki/List_of_dog_breeds>"
    page <- rvest::read_html(url)
    
    # Find table
    table <- page %>% html_nodes("table.wikitable.sortable")
    
    # Iterate rows
    table %>%
      html_nodes("tr") %>%
      .[. != 1] %>%
      html_nodes("td, th") %>%
      {
    
        # Extract data
        name <- html_text(.[[1]])
        group <- html_text(.[[2]])
    
        local_name <- html_text(.[[3]])
        if(local_name == "") {
          local_name <- NA
        }
    
        img_url <- xml_attr(.[[4]], "src")
    
        # Download image
        if(!is.na(img_url)){
    
          img <- GET(img_url)
          writeBin(img, paste0("dog_images/",name,".jpg"))
    
        }
    
        # Store data
        names <- c(names, name)
        groups <- c(groups, group)
        local_names <- c(local_names, local_name)
        photos <- c(photos, img_url)
    
      }
    

    This provides an R solution using rvest 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: