Web Scraping in R With rvest (Tested, 2026)
rvest web scraping, tested live - selectors, html_table, login forms, a 50-page crawl to 1,000 rows, JavaScript via read_html_live, measured timings.

On this page
Most rvest tutorials stop at read_html() plus one selector and call it
done. A scraper you can put on a schedule needs more than that: tables
with citation superscripts glued to the cells, logins, 50-page crawls,
and the JavaScript pages where rvest quietly hands you a zero-row data
frame. This rvest web scraping guide covers that path, and every code
block in it ran on 2026-11-02 with R 4.4.3 and rvest 1.0.5, the current
CRAN release; the timings and the failures are measured ones.
How rvest web scraping works
rvest is the tidyverse’s scraper. read_html() fetches and parses a
page through xml2 (a libxml2 binding), then you pull data out with CSS
selectors or XPath: html_elements() for matching nodes, html_text2()
for their text, html_attr() for attributes, html_table() for
tables. No browser, no engine to keep warm. That makes it the shortest
path from “I can see the data on this page” to “the data is in a data
frame”, with one hard boundary: it only sees what the server sends.
So run the decision test before writing any R. View the page source, or curl it and count the things you want:
curl -s https://quotes.toscrape.com/ | grep -c 'class="quote"'
10
The demo homepage ships all ten quotes in 11,064 bytes of server-rendered HTML. rvest is the right tool here. The same site publishes a JavaScript variant, and there the test fails:
curl -s https://quotes.toscrape.com/js/ | grep -c 'class="quote"'
0
That variant is a 5,808-byte shell; a script builds the quotes after the page loads. The static path can’t see them. What does work is in the JavaScript section below.
R isn’t the only language with this shape. Python’s BeautifulSoup tutorial runs the same test with the same outcome, and if your team already lives in Python, the Python scraping guide is the better starting point. Choose by the data stack that has to maintain the scraper, not by the language the tutorial used.
Setup
install.packages("rvest")
library(rvest)
packageVersion("rvest") # '1.0.5'
install.packages() pulls in xml2 for parsing and tibble for the output
shapes. I ran conda-forge binaries of the same version to keep R off the
system PATH; CRAN lists 1.0.5 as current, and that is what every receipt
below uses.
One translation note before you copy from older tutorials. rvest 1.0.0
(2022) renamed the API: html_nodes() became html_elements(), and
html_session() gave way to session(). The old names still work in
1.0.5 with warnings, but the development version has already deleted
them. Anything written before 2022 needs translating.
Step 1: Read a page and pull a data frame out
The quotes homepage puts each quote in a div.quote with the text, the
author, and a tag list inside. Select, coerce, done:
library(rvest)
pg <- read_html("https://quotes.toscrape.com/")
quotes <- tibble::tibble(
text = html_text2(html_elements(pg, ".quote .text")),
author = html_text2(html_elements(pg, ".quote .author")),
tags = sapply(html_elements(pg, ".quote .tags"), \(x)
paste(html_text2(html_elements(x, "a")), collapse = ", "))
)
nrow(quotes)
[1] 10
# A tibble: 2 × 3 (abridged)
text author tags
<chr> <chr> <chr>
1 "“The world as we have created it is a … Albert … change, deep-…
2 "“It is our choices, Harry, that show w… J.K. Ro… abilities, ch…
XPath works wherever CSS does, passed as
html_elements(pg, xpath = "//div[contains(@class,\"quote\")]"); the
examples here stick to CSS because it reads shorter.
Ten quotes, no error, a dozen lines of code. Now the two details that bite later.
First, html_text() versus html_text2(). The old html_text()
concatenates the raw text nodes with whatever whitespace the source
happens to contain. On an author page, .author-details comes back as
one blob where source indentation and <br> tags vanish:
au <- read_html("https://quotes.toscrape.com/author/Albert-Einstein")
cat(html_text(html_elements(au, ".author-details")))
Albert Einstein
Born: March 14, 1879 in Ulm, Germany
Description:
In 1879, Albert Einstein was born … warfare.At a symposium …
(abridged)
html_text2() approximates what a browser shows: line breaks where the
layout has them, no leading indentation mush. The rvest docs describe it
as slightly slower and, in rare cases, a different rendering than a
browser would produce. For scraping, html_text2() is the default you
want; reach for html_text() only when a regex needs the exact source
string.
Second, the silent empty result. Change a selector to .quote txt (a
typo) and you don’t get an error, a warning, or a stack trace. You get a
zero-row tibble, and write.csv() happily writes an empty file. Guard
anything you schedule:
stopifnot("no quotes found" = nrow(quotes) > 0)
Step 2: Take whole tables with html_table()
html_table() converts real <table> markup into data frames. Wikipedia
is the classic target because its infoboxes and wikitables are genuine
table elements, 24 rows on the Python page’s infobox:
wiki <- read_html("https://en.wikipedia.org/wiki/Python_(programming_language)")
tb <- html_table(html_elements(wiki, ".infobox"))
length(tb) # 1
dim(tb[[1]]) # 24 2
tb[[1]][2:4, ]
# A tibble: 3 × 2
Python Python
<chr> <chr>
1 Paradigm "Multi-paradigm: object-oriented,[1] procedural…
2 Designed by "Guido van Rossum"
3 Developer "Python Software Foundation"
Two things to notice. The first infobox row is the logo image, so it
arrives as an empty row; drop it with a filter. And the cells carry
citation markers straight from the page: object-oriented,[1] needs
gsub("\\[\\d+\\]", "", x) before the column joins anything. That is
Wikipedia’s wikitext bleeding through, not an rvest bug, and you will
meet it on every scraped table that supports its claims.
When html_table() returns an empty list, the “table” you saw in your
browser was drawn by JavaScript. Same silent-zero failure mode as Step
1, same fix: check before you write.
Step 3: Log in with session()
read_html() is one request, stateless. session() keeps cookies
between requests, which is what form logins need. The quotes site takes
any credentials:
s <- session("https://quotes.toscrape.com/login")
f <- html_form(s)[[1]]
f2 <- html_form_set(f, username = "demo", password = "demo")
s2 <- session_submit(s, f2)
s2$url
length(html_elements(s2, "a[href*='logout']")) # 1 = logged in
[1] "https://quotes.toscrape.com/"
[1] 1
The submit ran in 1.5 seconds and landed on the logged-in homepage. The proof of login is that logout link: the anonymous homepage has zero, this one has one. There is no “Login successful” banner to grep for, despite what several tutorials claim, so verify with an element that only exists in the authenticated DOM.
If your copy came from an old tutorial, it says html_session() and
set_values() and submit_form(). Those are the pre-1.0.0 names, and
the development version has deleted them. The session() pattern above
is the current one, and the general recipe for
scraping pages behind a login
covers the cases where the form is only the first obstacle.
Step 4: Crawl 50 pages, 1,000 rows, without being rude
books.toscrape.com spreads 1,000 books over 50 catalog pages. The loop is boring on purpose: build the URL, extract, sleep one second, repeat.
library(rvest)
books <- list()
for (p in 1:50) {
pg <- read_html(sprintf("https://books.toscrape.com/catalogue/page-%d.html", p))
nodes <- html_elements(pg, "article.product_pod")
books[[p]] <- tibble::tibble(
title = html_attr(html_elements(nodes, "h3 a"), "title"),
price = as.numeric(gsub("£", "", html_text2(html_elements(nodes, ".price_color")))),
rating = gsub("star-rating ", "",
html_attr(html_elements(nodes, "p.star-rating"), "class"))
)
Sys.sleep(1)
}
out <- do.call(rbind, books)
nrow(out)
write.csv(out, "books.csv", row.names = FALSE)
My run: 1,000 rows by 3 columns in 125.6 seconds including the 1-second
pauses, a 66,807-byte CSV, prices from 10 to 59.99 pounds, no parsing
failures. Each page serves 20 article.product_pod cards, so the count
also verifies nothing was dropped mid-crawl.
Now the trap that pure counting hides. length(unique(out$title))
returns 999, not 1,000. “The Star-Touched Queen” appears on page 12 at
46.02 and again on page 18 at 32.30: two different products, same title,
both real.
out[["page"]] <- rep(1:50, each = 20)
out[duplicated(out[["title"]]), ]
# A tibble: 1 × 4
title price rating page
<chr> <chr> <chr> <int>
1 The Star-Touched Queen 32.3 Five 18
A unique() call would silently delete one of them and understate the
catalog by a book. Dedup on title plus price instead and the check
returns zero rows, because the two copies differ in price: the trap
survives any key these three columns can build. Key on URL or SKU when
the site offers one; when titles are all you have, surface the
duplicates for a human instead of deleting them blind.
The pattern generalizes: pagination by predictable URL with sprintf(),
one second between requests, and a count check at the end. Deeper
variants (next-button crawls, infinite scroll) are in
the pagination guide, and
CSV and JSON output picks up where
write.csv() stops.
JavaScript pages: read_html_live()
Since rvest 1.0.4, the static failure has an in-package answer:
read_html_live() runs a real Chrome through the chromote package and
hands you the rendered page. Same selectors, same html_elements(),
after the JavaScript has done its work.
library(rvest)
p <- read_html_live("https://quotes.toscrape.com/js/")
length(html_elements(p, ".quote"))
[1] 10
That run took 3.0 seconds against Chrome for Testing 156.0.8078.4,
which chromote found through the CHROMOTE_CHROME environment
variable. Ten quotes from the page that static read_html() scored as
zero. The cost is real: you are paying for a browser process per
session, the same bill Puppeteer charges, and LiveHTML objects also
let you click, type, and scroll, which is where the maintenance
migrates when the site redesigns its buttons.
The rule from the decision test stands. Static HTML in the source:
read_html(), one second, done. Data drawn by scripts: read_html_live()
or give up. The wider playbook for rendered pages is in
scraping dynamic websites.
What rvest leaves to you
rvest ships no robots.txt handling and no rate limiter. Your Sys.sleep()
in Step 4 was the entire politeness system, which is exactly one
for-loop away from forgotten. The
polite package adds robots.txt
awareness and throttling on top of rvest and is worth wiring in before
anything you write touches a site you don’t own. One second between
requests is the floor I use for site-wide crawls; both toscrape demo
sites return 404 for robots.txt, so on real targets read the file first
and honor it.
When the goal is the data and not the R session, this is also the lane where a desktop scraper fits, and the reason I keep Magpie installed: fetch statically, escalate to a browser only when the page demands it, and get clean Markdown or JSON without writing extraction code per site. I still write rvest when the analysis lives in R anyway; extracting in Go and loading in R is a handoff I’d rather not own.
FAQ
Is rvest good for web scraping?
For server-rendered HTML, yes: 10 quotes extracted in one read_html()
call, and a 50-page, 1,000-row crawl in about two minutes including
politeness pauses. Its ceiling is pages that need JavaScript, where you
need read_html_live() and a Chrome install.
Can rvest scrape JavaScript-rendered pages?
Since 1.0.4, yes, through read_html_live(), which drives a real
browser via chromote. My run rendered the JS quote page in 3.0 seconds
where static read_html() saw a 5,808-byte shell with zero quotes. You
need Chrome and you pay browser-process costs.
rvest or BeautifulSoup?
Same niche, different languages: both parse server-rendered HTML you
fetch over HTTP. Pick rvest if the downstream analysis is R
(html_table() straight into data frames is the killer feature), pick
BeautifulSoup if it’s Python. Both need the same JS escape hatch for
rendered pages.
How do I scrape multiple pages with rvest?
Loop over predictable URLs with sprintf(), extract inside the loop,
Sys.sleep(1) between requests, rbind() the results. Verify with row
counts, not silence: my books crawl returned exactly 20 cards per page
and still hid a duplicate title across two pages.
Is web scraping with rvest legal? Public, non-authenticated pages scraped politely and slowly are the normal case, and that’s what this tutorial does. Logins, terms of service, and personal data change the analysis page by page, so check the target’s ToS and robots.txt before scheduling anything. This isn’t legal advice; it’s the checklist I run before the first request.
Start from the decision test, not the parser
curl -s <url> | grep -c '<your-data>'. A nonzero count means
read_html() plus html_elements() plus html_text2() gets you a data
frame in thirty lines, and the crawl scales by pasting a for loop
around it. A zero means Chrome enters the picture, and read_html_live()
since rvest 1.0.4 is the tidyverse-shaped way to pay that bill. Either
way, the stopifnot() row-count check from Step 1 costs one line and
saves the scheduled-run failure I’ve hit most often: a scraper that
works, then quietly writes nothing.


