Scraping Workshop

Part 1

library(tidyverse); library(rvest); library(polite)
Warning: package 'tidyverse' was built under R version 4.5.3
Warning: package 'tidyr' was built under R version 4.5.3
Warning: package 'readr' was built under R version 4.5.3
Warning: package 'dplyr' was built under R version 4.5.3
Warning: package 'stringr' was built under R version 4.5.3
Warning: package 'forcats' was built under R version 4.5.2
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.0     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.2
✔ purrr     1.0.4     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
Warning: package 'rvest' was built under R version 4.5.3

Attaching package: 'rvest'

The following object is masked from 'package:readr':

    guess_encoding
Warning: package 'polite' was built under R version 4.5.3
robotstxt::paths_allowed("https://books.toscrape.com/catalogue/")
books.toscrape.com
Warning in request_handler_handler(request = request, handler = on_not_found, :
Event: on_not_found
Warning in request_handler_handler(request = request, handler =
on_file_type_mismatch, : Event: on_file_type_mismatch
Warning in request_handler_handler(request = request, handler =
on_suspect_content, : Event: on_suspect_content
[1] TRUE
session <- bow("https://books.toscrape.com/",
user_agent = "EPPS6302 student; bjs170000@utdallas.edu",
delay = 5)
session
<polite session> https://books.toscrape.com/
    User-agent: EPPS6302 student; bjs170000@utdallas.edu
    robots.txt: 1 rules are defined for 1 bots
   Crawl delay: 5 sec
  The path is scrapable for this user-agent
parse_books <- function(pg) {
  pods <- html_elements(pg, "article.product_pod") # 20 books
  tibble(
    title = pods |> html_element("h3 a") |> html_attr("title"),
    price = pods |> html_element(".price_color") |> html_text2(),
    rating = pods |> html_element(".star-rating") |> html_attr("class"),
    stock = pods |> html_element(".availability") |> html_text2()
  )
}
pg1 <- nod(session, "catalogue/page-1.html") |> scrape()
No encoding supplied: defaulting to UTF-8.
books1 <- parse_books(pg1)
books1
# A tibble: 20 × 4
   title                                                      price rating stock
   <chr>                                                      <chr> <chr>  <chr>
 1 A Light in the Attic                                       £51.… star-… In s…
 2 Tipping the Velvet                                         £53.… star-… In s…
 3 Soumission                                                 £50.… star-… In s…
 4 Sharp Objects                                              £47.… star-… In s…
 5 Sapiens: A Brief History of Humankind                      £54.… star-… In s…
 6 The Requiem Red                                            £22.… star-… In s…
 7 The Dirty Little Secrets of Getting Your Dream Job         £33.… star-… In s…
 8 The Coming Woman: A Novel Based on the Life of the Infamo… £17.… star-… In s…
 9 The Boys in the Boat: Nine Americans and Their Epic Quest… £22.… star-… In s…
10 The Black Maria                                            £52.… star-… In s…
11 Starving Hearts (Triangular Trade Trilogy, #1)             £13.… star-… In s…
12 Shakespeare's Sonnets                                      £20.… star-… In s…
13 Set Me Free                                                £17.… star-… In s…
14 Scott Pilgrim's Precious Little Life (Scott Pilgrim #1)    £52.… star-… In s…
15 Rip it Up and Start Again                                  £35.… star-… In s…
16 Our Band Could Be Your Life: Scenes from the American Ind… £57.… star-… In s…
17 Olio                                                       £23.… star-… In s…
18 Mesaerion: The Best Science Fiction Stories 1800-1849      £37.… star-… In s…
19 Libertarianism for Beginners                               £51.… star-… In s…
20 It's Only the Himalayas                                    £45.… star-… In s…
stars <- c("One", "Two", "Three", "Four", "Five")
clean_books <- function(df) {
  df |> mutate(
    price = parse_number(price), # "£51.77" -> 51.77
    rating = match(str_remove(rating, "star-rating "), stars),
    in_stock = str_detect(stock, "In stock")
  ) |> select(-stock)
}
clean_books(books1)
# A tibble: 20 × 4
   title                                                   price rating in_stock
   <chr>                                                   <dbl>  <int> <lgl>   
 1 A Light in the Attic                                     51.8      3 TRUE    
 2 Tipping the Velvet                                       53.7      1 TRUE    
 3 Soumission                                               50.1      1 TRUE    
 4 Sharp Objects                                            47.8      4 TRUE    
 5 Sapiens: A Brief History of Humankind                    54.2      5 TRUE    
 6 The Requiem Red                                          22.7      1 TRUE    
 7 The Dirty Little Secrets of Getting Your Dream Job       33.3      4 TRUE    
 8 The Coming Woman: A Novel Based on the Life of the Inf…  17.9      3 TRUE    
 9 The Boys in the Boat: Nine Americans and Their Epic Qu…  22.6      4 TRUE    
10 The Black Maria                                          52.2      1 TRUE    
11 Starving Hearts (Triangular Trade Trilogy, #1)           14.0      2 TRUE    
12 Shakespeare's Sonnets                                    20.7      4 TRUE    
13 Set Me Free                                              17.5      5 TRUE    
14 Scott Pilgrim's Precious Little Life (Scott Pilgrim #1)  52.3      5 TRUE    
15 Rip it Up and Start Again                                35.0      5 TRUE    
16 Our Band Could Be Your Life: Scenes from the American …  57.2      3 TRUE    
17 Olio                                                     23.9      1 TRUE    
18 Mesaerion: The Best Science Fiction Stories 1800-1849    37.6      1 TRUE    
19 Libertarianism for Beginners                             51.3      2 TRUE    
20 It's Only the Himalayas                                  45.2      2 TRUE    
get_page <- function(i) {
nod(session, paste0("catalogue/page-", i, ".html")) |>
scrape() |> parse_books() |> mutate(page = i)
}
books_raw <- map(1:50, get_page) |> list_rbind() # waits 5 s a page
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
No encoding supplied: defaulting to UTF-8.
dir.create("data", showWarnings = FALSE)
write_csv(books_raw, "data/books_raw.csv") # cache the raw pull
books <- clean_books(books_raw)
print(mean(books$price))
[1] 35.07035

books.toscrape Data collected: text permission: terms Method: selector Cleaning rules: NA Known gaps: NA

Checkpoint A.

What is the mean price by rating? The mean price of the books is £34.56

Which line breaks first if the site is redesigned? The parse books function will break as it needs the html tags to remain consistent.

Part 2

count_quotes <- function(url) {
  read_html(url) |> html_elements(".quote") |> length()
}
count_quotes("https://quotes.toscrape.com/")
[1] 10
count_quotes("https://quotes.toscrape.com/js/")
[1] 0

Where are the quotes in the source? The quotes are located under the quote element under the page.

library(httr2)
Warning: package 'httr2' was built under R version 4.5.3
ua <- "EPPS6302 student; bjs170000@utdallas.edu"
get_quotes <- function(page) {
  Sys.sleep(1) # one request a second
  request("https://quotes.toscrape.com/api/quotes") |>
  req_url_query(page = page) |>
  req_user_agent(ua) |>
  req_retry(max_tries = 3) |>
  req_perform() |>
  resp_body_json()
}
j <- get_quotes(1)
names(j) # has_next, page, quotes, tag, top_ten_tags
[1] "has_next"     "page"         "quotes"       "tag"          "top_ten_tags"
rectangle <- function(quote_list) {
  tibble(q = quote_list) |>
  unnest_wider(q) |> # author, tags, text
  hoist(author, author_name = "name", author_slug = "slug") |>
  mutate(tags = map_chr(tags,
   \(x) paste(unlist(x), collapse = "; "))) |>
  select(text, author_name, author_slug, tags)
}
print(Sys.time())
[1] "2026-10-13 16:38:44 CDT"
rectangle(j$quotes)
# A tibble: 10 × 4
   text                                            author_name author_slug tags 
   <chr>                                           <chr>       <chr>       <chr>
 1 “The world as we have created it is a process … Albert Ein… Albert-Ein… chan…
 2 “It is our choices, Harry, that show what we t… J.K. Rowli… J-K-Rowling abil…
 3 “There are only two ways to live your life. On… Albert Ein… Albert-Ein… insp…
 4 “The person, be it gentleman or lady, who has … Jane Austen Jane-Austen alit…
 5 “Imperfection is beauty, madness is genius and… Marilyn Mo… Marilyn-Mo… be-y…
 6 “Try not to become a man of success. Rather be… Albert Ein… Albert-Ein… adul…
 7 “It is better to be hated for what you are tha… André Gide  Andre-Gide  life…
 8 “I have not failed. I've just found 10,000 way… Thomas A. … Thomas-A-E… edis…
 9 “A woman is like a tea bag; you never know how… Eleanor Ro… Eleanor-Ro… misa…
10 “A day without sunshine is like, you know, nig… Steve Mart… Steve-Mart… humo…
print(Sys.time())
[1] "2026-10-13 16:38:44 CDT"
pages <- list(); p <- 1
print(Sys.time())
[1] "2026-10-13 16:38:45 CDT"
repeat {
pages[[p]] <- get_quotes(p)
if (!pages[[p]]$has_next) break
p <- p + 1
}
quotes <- map(pages, "quotes") |> list_flatten() |> rectangle()
print(Sys.time())
[1] "2026-10-13 16:38:56 CDT"
write_csv(quotes, "data/quotes.csv")
live <- read_html_live("https://quotes.toscrape.com/js/")
live |> html_elements(".quote .text") |> html_text2() # ten quotes
 [1] "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”"                
 [2] "“It is our choices, Harry, that show what we truly are, far more than our abilities.”"                                              
 [3] "“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”"
 [4] "“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”"                           
 [5] "“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”"                    
 [6] "“Try not to become a man of success. Rather become a man of value.”"                                                                
 [7] "“It is better to be hated for what you are than to be loved for what you are not.”"                                                 
 [8] "“I have not failed. I've just found 10,000 ways that won't work.”"                                                                  
 [9] "“A woman is like a tea bag; you never know how strong it is until it's in hot water.”"                                              
[10] "“A day without sunshine is like, you know, night.”"                                                                                 
live$view() 
nrow(quotes)
[1] 100

quotes.toscrape Data collected: text permission: terms Method: selector Cleaning rules: NA Known gaps: NA

Checkpoint B.

nrow(quotes) is 100 from 10 pages. Routes 1 and 2 return the same text for page 1 — which was faster, and which made fewer demands on the server? Which would survive a redesign of the page?

The first routes is much faster and will have made less demands as it does not need to look at the website in a loop. The second option appears to have more resilient to the website changes as it just reads the quotes and text and does not need to unpack the text on the website.

Part 3:

yt <- request("https://www.googleapis.com/youtube/v3/videos") |>
req_url_query(part = "snippet,statistics", chart = "mostPopular",
regionCode = "US", maxResults = 10,
key = Sys.getenv("YOUTUBE_API_KEY")) |>
req_perform() |> resp_body_json()
tibble(v = yt$items) |> unnest_wider(v) |>
hoist(snippet, title = "title", channel = "channelTitle") |>
hoist(statistics, views = "viewCount") |>
select(id, title, channel, views)
# A tibble: 10 × 4
   id          title                                               channel views
   <chr>       <chr>                                               <chr>   <chr>
 1 bLECYvOdQPQ "Riley Green, Peyton Manning - Alabama Vs. Tenness… "Riley… 2951…
 2 ox8lEnsxDag "River | Official Trailer"                          "Unive… 2620…
 3 -2F6T9LiESs "I’ve Never Been This Scared In Minecraft…"         "CaseO… 8881…
 4 C58utn68Qho "Saii Kay - Iau Tar Les (ft. Heff Lourie, Maix Kay… "Saii … 43369
 5 KXO21xZdUaM "Hexed | Official Trailer"                          "Walt … 2943…
 6 IojD4uQCCvo "\U0001f534LIVE | ARC RAIDERS DUOS w/ GIMMICK | NE… "TheBu… 1069…
 7 2ZTcvsdMR1c "Ayra Starr - Heaven Baby ft. ZAYN"                 "AyraS… 9514…
 8 fXz5DcshZ4g "Hood Warfare 2 Official Trailer"                   "Traps… 2177…
 9 q0DFDWSNzT4 "The Most Controversial Game of 2026"               "Asmon… 9937…
10 8aKR2Ho--5k "MEOVV(미야오) - ‘GO HARD’ M/V"                     "THEBL… 8112…

YouTube Data collected: url, title, channel, and viewcount permission: api Method: selector Cleaning rules: Max 10 of US Known gaps: NA