ZetCode

R web scraping

last modified November 20, 2026

A web page is a text file written in HTML, and scraping means reading that file programmatically instead of with a browser. The rvest package parses HTML into a tree of nodes and selects parts of it with CSS selectors: a tag name such as h1, a class such as .price, or a descendant combination such as div.quote small.author. The selected nodes yield text, attributes, or whole tables as data frames. This article extracts text, links, attributes, and tables, builds one record per repeated block, handles missing elements, follows pagination, and caches pages on disk. The examples use rvest 1.0.5 and R 4.5.2.

The live examples use two websites built for scraping practice: quotes.toscrape.com, a list of quotes spread over several pages, and books.toscrape.com, a fictional bookshop with prices and ratings. Their content does not change, so the output shown here stays valid. The examples need the rvest package, which is not part of base R. Install it once with install.packages("rvest"); the installing packages section of the introduction explains the details.

Parsing an HTML string

read_html parses HTML and returns an xml_document. It accepts a file name, a URL, or the HTML text itself, which is the quickest way to try a selector. html_element returns the first node that matches a CSS selector, html_elements returns all matching nodes, and html_text extracts the text of a node without the tags.

parse-string.R
library(rvest)
html <- '<h1>Bookshop news</h1>
<p class="note">New titles arrive on Friday.</p>
<p>Opening hours: 9 to 17.</p>'
page <- read_html(html)
cat("heading:", html_text(html_element(page, "h1")), "\n")
cat("note:", html_text(html_element(page, ".note")), "\n")
cat("paragraphs:", length(html_elements(page, "p")), "\n")

The selector h1 matches by tag name and .note by class. The string has no html or body tags; read_html adds them while parsing, just as a browser does. The page holds two paragraphs, so html_elements returns two nodes.

$ Rscript parse-string.R
heading: Bookshop news 
note: New titles arrive on Friday. 
paragraphs: 2 

A first live page

Given a URL, read_html downloads the page and parses it. The result is the same kind of document as before, so the selector code does not care where the HTML came from. The script reads the document title and counts the quote blocks and the links on the first page of the quotes site.

first-page.R
library(rvest)
page <- read_html("https://quotes.toscrape.com/")
cat("title:", html_text(html_element(page, "title")), "\n")
cat("quotes:", length(html_elements(page, "div.quote")), "\n")
cat("links:", length(html_elements(page, "a")), "\n")

The page holds ten quotes, each in a div element with the class quote, and fifty-five links in total, counting the author links, the tag links, and the navigation. Viewing the page source in a browser, or using its developer tools, is the usual way to find the tags and classes that a scraper should select.

$ Rscript first-page.R
title: Quotes to Scrape 
quotes: 10 
links: 55 

Selecting elements with CSS

A CSS selector describes a position in the tree. A space between two parts makes a descendant selector: div.quote small.author matches the small elements with the class author that lie inside a quote block. Subsetting a nodeset with [ works like subsetting a vector. html_text2 returns the text as a browser would show it, while html_text returns it exactly as written in the source.

selectors.R
library(rvest)
page <- read_html("https://quotes.toscrape.com/")
authors <- html_elements(page, "div.quote small.author")
print(html_text2(authors[1:4]))
texts <- html_elements(page, "div.quote span.text")
cat("first:", html_text2(texts[1]), "\n")
heading <- html_element(page, "h1")
print(html_text(heading))
print(html_text2(heading))

The first four authors come back as a character vector, with Albert Einstein appearing twice. The quote text keeps its typographic quotation marks, because they are part of the page content. The heading shows the difference between the two text functions: in the source it is indented over three lines, so html_text returns the newlines and spaces, while html_text2 collapses them. Use html_text2 for values that people will read.

$ Rscript selectors.R
[1] "Albert Einstein" "J.K. Rowling"    "Albert Einstein" "Jane Austen"    
first: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” 
[1] "\n                    Quotes to Scrape\n                "
[1] "Quotes to Scrape"

Reading attributes

Text is only one part of a node. Links carry their destination in the href attribute, and a scraper usually needs that value rather than the visible label. html_attr returns the value of one attribute for every node in a set. The author links on the quotes page are relative, so url_absolute combines them with the page address into full URLs.

link-attrs.R
library(rvest)
url <- "https://quotes.toscrape.com/"
page <- read_html(url)
links <- html_elements(page, "div.quote span a")
hrefs <- html_attr(links, "href")
print(head(hrefs, 3))
full <- url_absolute(hrefs, url)
print(head(full, 3))
cat("unique authors:", length(unique(full)), "\n")

Each quote has an "(about)" link to its author's page. The href values start with a slash, which means they are relative to the root of the site, and url_absolute resolves them the same way a browser does. The ten quotes on the page come from eight different authors, so unique leaves eight addresses to visit.

$ Rscript link-attrs.R
[1] "/author/Albert-Einstein" "/author/J-K-Rowling"    
[3] "/author/Albert-Einstein"
[1] "https://quotes.toscrape.com/author/Albert-Einstein"
[2] "https://quotes.toscrape.com/author/J-K-Rowling"    
[3] "https://quotes.toscrape.com/author/Albert-Einstein"
unique authors: 8 

Attributes as data

Attributes often hold data that the visible text lacks. On the bookshop page, long titles are cut short in the link text, but the full title is kept in the title attribute. The star rating has no text at all: it is drawn by the style sheet from a class name such as star-rating Three. The class attribute is read like any other.

book-attrs.R
library(rvest)
page <- read_html("https://books.toscrape.com/")
links <- html_elements(page, "article.product_pod h3 a")
cat("shown:", html_text2(links[1]), "\n")
cat("title:", html_attr(links[1], "title"), "\n")
stars <- html_attr(html_elements(page, "p.star-rating"), "class")
print(head(stars, 3))
words <- sub("star-rating ", "", stars)
rating <- match(words, c("One", "Two", "Three", "Four", "Five"))
print(table(rating))

The link text ends with three dots, while the attribute holds the complete title. sub removes the common part of the class name, and match turns the remaining word into its position in the vector of rating words, which is the number of stars. table then counts the twenty books on the first page by rating.

$ Rscript book-attrs.R
shown: A Light in the ... 
title: A Light in the Attic 
[1] "star-rating Three" "star-rating One"   "star-rating One"  
rating
1 2 3 4 5 
6 3 3 4 4 

Extracting tables

HTML tables are common on pages that list prices, schedules, or statistics, and html_table converts them directly. It returns a list with one data frame per table on the page, because a page can hold several. The product page of a book has a table of details in which every row starts with a header cell, so header = FALSE keeps the first row as data.

tables.R
library(rvest)
url <- "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"
page <- read_html(url)
tables <- html_table(page, header = FALSE)
cat("tables:", length(tables), "\n")
info <- tables[[1]]
names(info) <- c("field", "value")
print(info)
cat("availability:", info$value[info$field == "Availability"], "\n")

The page contains one table, and its seven rows become a tibble with two columns, renamed to field and value. All values are strings, because the column mixes codes, prices, and text. A logical index selects the value of a single field. With fill = TRUE, html_table pads short rows with NA, so a ragged table still becomes a rectangular frame.

$ Rscript tables.R
tables: 1 
# A tibble: 7 × 2
  field             value                  
  <chr>             <chr>                  
1 UPC               a897fe39b1053632       
2 Product Type      Books                  
3 Price (excl. tax) £51.77                 
4 Price (incl. tax) £51.77                 
5 Tax               £0.00                  
6 Availability      In stock (22 available)
7 Number of reviews 0                      
availability: In stock (22 available) 

Building records

Most pages repeat a block of markup instead of using a table. On the bookshop page, each book is an article element with the class product_pod, and the scraper turns one block into one row. html_element is vectorised over a nodeset: given all twenty blocks and the selector p.price_color, it returns the price of each block. The prices start with a pound sign, which sub removes before as.numeric converts the values.

records.R
library(rvest)
page <- read_html("https://books.toscrape.com/")
books <- html_elements(page, "article.product_pod")
titles <- html_attr(html_element(books, "h3 a"), "title")
prices <- html_text2(html_element(books, "p.price_color"))
prices <- as.numeric(sub("£", "", prices))
records <- data.frame(title = substr(titles, 1, 30), price = prices)
print(head(records))
cat("books:", nrow(records), "\n")
cat("mean price:", round(mean(prices), 2), "\n")

The first page lists twenty books, and the data frame has one row per book. The titles are shortened with substr to keep the printout narrow. Selecting the blocks first and the fields inside each block second keeps the values of one book together in the same row.

$ Rscript records.R
                           title price
1           A Light in the Attic 51.77
2             Tipping the Velvet 53.74
3                     Soumission 50.10
4                  Sharp Objects 47.82
5 Sapiens: A Brief History of Hu 54.23
6                The Requiem Red 22.65
books: 20 
mean price: 38.05 

Missing elements

Real pages are not always regular: a book may have no price or a product no picture. The bookshop has no such gaps, so this example uses a short HTML string in which the second book lacks its price. When a selector matches nothing inside a block, html_element does not drop the position; it returns a missing node, and the text functions turn that node into NA.

missing-nodes.R
library(rvest)
html <- '<div class="book"><h2>R in Action</h2><span class="price">45</span></div>
<div class="book"><h2>R Cookbook</h2></div>
<div class="book"><h2>R Graphics</h2><span class="price">38</span></div>'
books <- html_elements(read_html(html), "div.book")
titles <- html_text2(html_element(books, "h2"))
cat("all prices:", length(html_elements(books, ".price")), "\n")
price_nodes <- html_element(books, ".price")
print(price_nodes)
prices <- as.numeric(html_text2(price_nodes))
print(data.frame(title = titles, price = prices))

html_elements searches all blocks together and finds only two prices, so pairing its result with the three titles would shift the rows. html_element returns one entry per block, with NA in the second position, and the data frame keeps each price next to its title.

$ Rscript missing-nodes.R
all prices: 2 
{xml_nodeset (3)}
[1] <span class="price">45</span>
[2] NA
[3] <span class="price">38</span>
        title price
1 R in Action    45
2  R Cookbook    NA
3  R Graphics    38

Following pages

A listing that does not fit on one page has a link to the next one. The quotes site puts it in a list item with the class next. The loop reads a page, collects the authors, and resolves the next link into a full URL. On the last page the link is missing, html_attr returns NA, and break ends the loop early.

pages.R
library(rvest)
url <- "https://quotes.toscrape.com/"
authors <- character()
for (i in 1:3) {
  page <- read_html(url)
  found <- html_text2(html_elements(page, "div.quote small.author"))
  cat("page", i, "quotes:", length(found), "\n")
  authors <- c(authors, found)
  next_link <- html_attr(html_element(page, "li.next a"), "href")
  if (is.na(next_link)) break
  url <- url_absolute(next_link, url)
  Sys.sleep(1)
}
cat("next page:", url, "\n")
cat("quotes:", length(authors), "\n")
print(head(sort(table(authors), decreasing = TRUE), 3))

The loop stops after three pages, which is enough for the example; the whole site has ten. Sys.sleep(1) waits a second between requests, so a loop over many pages does not overload the server. The table of authors shows that Albert Einstein is quoted most often on the first three pages.

$ Rscript pages.R
page 1 quotes: 10 
page 2 quotes: 10 
page 3 quotes: 10 
next page: https://quotes.toscrape.com/page/4/ 
quotes: 30 
authors
Albert Einstein    J.K. Rowling      Bob Marley 
              6               3               2 

Caching pages

Getting selectors right takes several attempts, and downloading the same pages on every attempt is slow and impolite. download.file saves a page to disk, and read_html parses the saved file just as it parses a URL. The script downloads the page only when the file does not exist yet.

cache.R
library(rvest)
url <- "https://books.toscrape.com/catalogue/category/books/travel_2/index.html"
file <- "travel.html"
if (!file.exists(file)) {
  cat("downloading\n")
  download.file(url, file, quiet = TRUE)
} else {
  cat("using the saved copy\n")
}
page <- read_html(file)
cat("heading:", html_text2(html_element(page, "h1")), "\n")
cat("books:", length(html_elements(page, "article.product_pod")), "\n")

The first run downloads the Travel category page; the second run finds travel.html and parses it without contacting the server. The results are the same both times. Deleting the file forces a fresh download. For a larger scrape, save each page under its own name, so that a failed run can resume where it stopped.

$ Rscript cache.R
downloading
heading: Travel 
books: 11 
$ Rscript cache.R
using the saved copy
heading: Travel 
books: 11 

A complete example

The final script combines the techniques on the Travel category of the bookshop. A helper function parses one book block into a one-row data frame with the full title, the price, and the rating word. The rows are bound together, the price and the rating become numbers, and the books are sorted by rating and then by price.

complete.R
library(rvest)
url <- "https://books.toscrape.com/catalogue/category/books/travel_2/index.html"
page <- read_html(url)
books <- html_elements(page, "article.product_pod")
parse_book <- function(book) {
  stars <- html_attr(html_element(book, "p.star-rating"), "class")
  data.frame(
    title = html_attr(html_element(book, "h3 a"), "title"),
    price = html_text2(html_element(book, "p.price_color")),
    rating = sub("star-rating ", "", stars)
  )
}
records <- do.call(rbind, lapply(books, parse_book))
records$title <- substr(records$title, 1, 28)
records$price <- as.numeric(sub("£", "", records$price))
records$rating <- match(records$rating, c("One", "Two", "Three", "Four", "Five"))
records <- records[order(-records$rating, records$price), ]
print(records[, c("title", "price", "rating")], row.names = FALSE)
cat("books:", nrow(records), "\n")
cat("average price:", round(mean(records$price), 2), "\n")
cat("five stars:", sum(records$rating == 5), "\n")

The category holds eleven books with an average price of 39.79, and one of them has five stars. do.call(rbind, ...) stacks the one-row frames, because rbind does not accept a list directly. The minus sign in order sorts the ratings in descending order, and the prices break ties. The helper keeps the selector for each field in one place, which makes the script easy to adjust when the page changes.

$ Rscript complete.R
                        title price rating
 1,000 Places to See Before Y 26.08      5
 Full Moon over Noah’s Ark: A 49.43      4
 A Year in Provence (Provence 56.88      4
         Under the Tuscan Sun 37.33      3
 Neither Here nor There: Trav 38.95      3
 See America: A Celebration o 48.87      3
 Vagabonding: An Uncommon Gui 36.94      2
           A Summer In Europe 44.34      2
      It's Only the Himalayas 45.17      2
 The Road to Little Dribbling 23.21      1
     The Great Railway Bazaar 30.54      1
books: 11 
average price: 39.79 
five stars: 1 

Source

rvest: easily harvest web pages

rvest on CRAN

Toscrape: web scraping sandbox

MDN: CSS selectors

RFC 9309: Robots Exclusion Protocol

In this article we parsed HTML from a string and from live pages, selected nodes with tag, class, and descendant selectors, and read text and attributes. We resolved relative links, decoded ratings from class names, converted a table into a tibble, and built one record per repeated block. Missing elements became NA instead of shifting the rows, a loop followed the next-page links, and a saved copy spared the server repeated downloads. Before scraping other sites, read their robots.txt file and terms of use. The strings and regular expressions articles cover the functions used to clean scraped text, and the HTTP requests article shows how to call a data API directly when a site offers one.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.