Tidy web scraping in R — Tutorial and resources

I used to think web scraping sounded complicated. You’d have to decode a bunch of HTML and Javascript and do messy hacking to get at what you wanted.

But once I took a crack at it using my favourite language of R, I realized that tools exist to make it very tidy and straightforward, and I was surprised by how quickly and easily I was pulling facts, tables, images and various other assets from websites.

So I’ve written up a step by step guide to get you started. You can also find the Markdown version of this guide and the various functions and assets I created here so you can execute them in your R session.

Hope you find this helpful!

1. Web Page Structure and Format

Any webpage you visit has a particular, expected general structure. It usually consists of two types of code.

  • HTML code, which focuses on the appearance and format of a web page.
  • XML code, which doesn’t look a lot different from HTML but focuses more on managing data in a web page.

1.1 HTML code

HTML code has an expected format and structure, to make it easy for people to develop web pages. Here is an example of a simple HTML page:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

As you can see, the content is wrapped in tags like <head>, <body>, <p>. These tags are pre-defined by the language (you can only use the tags that HTML allows). Because HTML has a more predictable structure, it is often easier to work with it and mine it.

1.2 XML code

XML format and structure is less predictable. Although it looks very similar to HTML, users can create their own named tags. Here is an example:

<note>
<to>Keith</to>
<from>Steve</from>
<heading>Kudos</heading>
<body>Awesome work, dude!</body>
</note>

Tags like <to> and <from> are completely made up by me. The fact that tags are not pre-defined makes XML a little harder to mine and analyze. But it’s hard to get at some of the data on the web without using XML.

1.3 Using Google Chrome Developer

To mine web data, it’s important that you can see the underlying code and understand how it relates to what you are seeing on the page. The best way to do this (in my opinion) is to use the Developer Tools that come with Google Chrome.

When you are viewing a web page in Chrome, simply used Ctrl+Shift+C in Windows or Cmd+Option+C on a Mac to open up the Elements console where you can see all the code underlying the page. This can look really complex, but don’t worry. Here’s a photo of Google Chrome Developer open on the Billboard Hot 100 page:

The Billboard Hot 100 page with Chrome Elements open

1.4 Embedded structure of web code

If you play around with the code in the Developer you will see that it has an embedded structure.

  • At the highest level there is a <html>tag.
  • At the second level there are <head> and <body> tags.
  • Inside the <body> of the page, different elements are often separated by <div> tags.
  • Many different types of tags continue to be embedded down to many nested levels

This is important because it means we can mine elements of a web page and treat them like lists in R. We often call a specific element of the page a node. So if we want to mine a specific node, we can capture its sub-nodes in a list. By doing so, this gives us the opportunity to apply the tidyverse when mining web pages. The process of mining data from the web is called scraping or harvesting.

1.5 The rvest and xml2 packages

The rvestand xml2packages were designed to make it easier for people working in R to harvest web data. Since xml2 is a required package for rvest and the idea is that both packages work together, you only need to install rvest. First, let’s ensure the packages we need are installed and loaded:

if (!(“rvest” %in% installed.packages())) {
install.packages(“rvest”)
}
if (!(“dplyr” %in% installed.packages())) {
install.packages(“dplyr”)
}
library(rvest)
library(dplyr)

rvest and xml2 contain functions that allow us to read the code of a web page, break it into a neat structure, and work with the pipe command to efficiently find and extract specific pieces of information. Think of it a bit like performing keyhole surgery on a webpage. Once you understand what functions are available and what they do, it makes basic web scraping very easy and can produce really powerful functionality.

2. Basic harvesting: The Billboard Hot 100 page

We are going to use the example of mining the Billboard Hot 100 page at https://www.billboard.com/charts/hot-100. If you view this page, it’s pretty bling. There are videos popping up, images all over the place. But the basic point of the page is to show the current Hot 100 chart.

So let’s set ourselves the task of just harvesting the basic info from this page: Position Number, Artist, Song Title for the Hot 100.

2.1 Getting started

First we load our packages and then we use the function read_html() to capture the HTML code of the Billboard Hot 100 page.

hot100page <- “https://www.billboard.com/charts/hot-100"
hot100 <- read_html(hot100page)
hot100
str(hot100)

The output should be:

{xml_document}
<html class="" lang="">
[1] <head>n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">n<script>n _udn = "billboard.com";n ...
[2] <body class="chart-page chart-page- " data-trackcategory="Charts-TheHot100" data-content-type="chart">n<div class="heade ...
List of 2
$ node:<externalptr>
$ doc :<externalptr>
- attr(*, "class")= chr [1:2] "xml_document" "xml_node"

The function has captured the entire content of the page in the form of a special list-type document with two nodes <head> and <body>. Almost always we are interested in the body of a web page. You can select a node using html_node() and then see its child nodes using html_children().

body_nodes <- hot100 %>% 
html_node(“body”) %>%
html_children()
body_nodes

This should give you a list of nodes inside the body of the page.

If we want, we can go one level deeper, to see the nodes inside the nodes. In this way, we can just continue to pipe deeper into the code. Try:

body_nodes %>% 
html_children()

2.2 Forensically targeting information of interest

So we could mess around with the functions above for a long time, but might find it hard to work out where exactly this chart data is. We can use Chrome Developer to tell us where we can find the data in the code, and then we can use rvest to harvest out the data.

If you run your mouse over the code in the Developer you will see that the elements of the page that the code refers to are highlighted in the browser. You can click to expand embedded nodes to get to more specific parts of the page. You can watch the video I added to this repo to see how I progressively drill down the code to find the precise nodes that contain the details of each chart entry (note this video uses a previous version of the site but you’ll get the idea).

What we see is that each chart entry appears to be in <span> tag with the class names chart-element__rank__numberchart-element__information__artist and chart-element__information__song.

Now we can use the function xml_find_all() to find all <span> nodes in the body of the document that have a class name containing the class names we want. xml_find_all() accepts xpath syntax. You can learn more about xpath syntax here. Once those precise nodes are located, we can use the rvest function html_text() to simply extract the info we want:

rank <- hot100 %>% 
rvest::html_nodes('body') %>%
xml2::xml_find_all("//span[contains(@class, 'chart-element__rank__number')]") %>%
rvest::html_text()

artist <- hot100 %>%
rvest::html_nodes('body') %>%
xml2::xml_find_all("//span[contains(@class, 'chart-element__information__artist')]") %>%
rvest::html_text()

title <- hot100 %>%
rvest::html_nodes('body') %>%
xml2::xml_find_all("//span[contains(@class, 'chart-element__information__song')]") %>%
rvest::html_text()

That’s the Billboard Hot 100! Nice! Now we can combine them all into a neat dataframe.

chart_df <- data.frame(rank, artist, title)knitr::kable(
chart_df %>% head(10)

3. Making scraping easy by automating tasks

Generally we don’t just scrape a single webpage for fun. We are usually scraping because there is information that we need on a large scale or on a regular basis. Therefore, once you have worked out how to scrape this information, you’ll need to set things up in a way that it is easy to obtain it in the future. Writing functions is often a good way of doing this.

3.1 Example: Writing a function to grab any Billboard chart from history

If you take a look around the billboard site, you’ll see that you can basically look up any chart at any date in history by simply inserting the chart name and date at the appropriate point in the URL. For example, to see the Billboard 200 on 21st July 1972 you would navigate to https://www.billboard.com/charts/billboard-200/1972-07-21.

Since this will always produce a webpage in exactly the same structure as the one we just scraped, we can now create quite a powerful function that accepts a chart name, date and set of ranks, and returns the entries for that chart on that date in those ranks.

get_chart <- function(date = Sys.Date(), positions = c(1:10), type = "hot-100") {
  # get url from input and read html
  input <- paste0("https://www.billboard.com/charts/", type, "/", date) 
  chart_page <- xml2::read_html(input)
  
  # scrape data
  rank <- chart_page %>% 
    rvest::html_nodes('body') %>% 
    xml2::xml_find_all("//span[contains(@class, 'chart-element__rank__number')]") %>% 
    rvest::html_text()
  
  artist <- chart_page %>% 
    rvest::html_nodes('body') %>% 
    xml2::xml_find_all("//span[contains(@class, 'chart-element__information__artist')]") %>% 
    rvest::html_text()
  
  title <- chart_page %>% 
    rvest::html_nodes('body') %>% 
    xml2::xml_find_all("//span[contains(@class, 'chart-element__information__song')]") %>% 
    rvest::html_text()
  # create dataframe, remove nas and return result
  chart_df <- data.frame(rank, artist, title)
  chart_df <- chart_df %>% 
    dplyr::filter(!is.na(rank), rank %in% positions)
chart_df
}

Now let’s test our function by looking up the Top 10 singles from 20th January 1975:

test <- get_chart(date = “1975–01–20”, positions = 1:10, type = “hot-100”)
test

You should discover that this was Number 1 on that date.

The Carpenters

3.2 Example: Writing a function to grab any set of Eurovision Song Contest results

Similarly, we can create a function `get_eurovision()` to scrape the results of any Eurovision Song Contest since 1957. You can get the function here and then grab the 1974 contest results:

source(“eurovision_scraping.R”)
eurovision_1974 <- get_eurovision(1974)
eurovision_1974

Oh man, look who won it that year:

3.3 Example: Packaging wikifacts

Recently I thought it might be useful to have a package that generated random facts for people. This could be helpful for scripts or apps that take a long time to execute, where you could occasionally display random facts to keep people interested.

The Wikipedia Main Page has three predictable sections which can be reliably scraped. So I used them to create three functions:

  • wiki_didyouknow() which takes random facts from the ‘Did you know…’ section
  • wiki_onthisday() which takes random facts from the ‘On this day…’ section
  • wiki_inthenews() which takes random facts from the ‘In the news…’ section

A fourth function wiki_randomfact() executes one of the above three functions at random.

I packaged this into a package called `wikifacts` which can be installed from CRAN. Here’s some examples of the functions at work:

install.packages("wikifacts")
library(wikifacts)
wiki_didyouknow()
Did you know that President Gerald Ford delayed the signing ceremony for the 1974 Jackson–Vanik amendment because Mark E. Talisman's wife was in labor? (Courtesy of Wikipedia)
wiki_onthisday()
Did you know that on this day in 2009 – At the World Championships in Athletics in Berlin, Usain Bolt ran the 100 metres in 9.58 seconds, breaking his own record set a year earlier. (Courtesy of Wikipedia)

Wow, look how much we’ve achieved. I hope this encourages you to take on some web scraping for work or fun. I really enjoyed learning about it!

Leave a Reply

%d bloggers like this: