Web scraping
Web scraping with R
R is at its best when data ends up in a data frame, and scraping is just the first step of that journey. With httr2 for requests and rvest for parsing, a few piped lines turn a public page into tidy rows.
The two packages
httr2 builds HTTP requests as pipelines: you start with request(url) and add steps such as a user agent, a timeout, retries and throttling, then call req_perform(). rvest reads HTML and gives you functions to select elements and pull text, attributes and tables. rvest can fetch pages by itself with read_html(url), which is fine for a quick look, but httr2 gives you control over retries, rate limits and errors, which matters as soon as a script runs unattended.
install.packages(c("httr2", "rvest"))
library(httr2)
library(rvest)
The examples use the native pipe |> and the short lambda syntax \(x), both available from R 4.1.
A polite request template
Build one base request with everything every call needs, then derive page specific requests from it. httr2 requests are plain values, so modifying a copy never changes the template.
base_req <- request("https://stats.example.org") |>
req_user_agent("Mozilla/5.0 (X11; Linux x86_64) r-research-bot/1.0 (+mailto:data@example.org)") |>
req_headers(`Accept-Language` = "en-US,en;q=0.8") |>
req_timeout(25) |>
req_retry(max_tries = 4, backoff = \(attempt) 2^attempt) |>
req_throttle(rate = 20 / 60)
req_retry() retries transient failures, by default 429 and 503 responses, and honors Retry-After. The custom backoff doubles the wait after each attempt. req_throttle(rate = 20 / 60) caps requests at twenty per minute for this host across the whole session, so a loop cannot accidentally run faster than you intended. Argument names follow httr2 1.x at the time of writing; see the package reference if a newer release changes them.
Fetching and parsing one page
resp <- base_req |>
req_url_path("/regions/indicators") |>
req_url_query(year = 2024, page = 1) |>
req_perform()
page <- resp_body_html(resp)
cards <- page |> html_elements("div.indicator")
indicators <- data.frame(
name = cards |> html_element("h3") |> html_text2(),
value = cards |> html_element(".value") |> html_text2() |> readr::parse_number(),
link = cards |> html_element("a") |> html_attr("href") |> url_absolute(resp_url(resp))
)
The pattern html_elements() then html_element() is the key idiom in rvest. The first finds every card; the second finds one child per card and returns a missing value when a card lacks it, so the columns always line up row for row. html_text2() trims and normalizes white space the way a browser would display it. url_absolute() comes from xml2, which rvest loads, and turns relative links into full URLs. readr::parse_number strips currency symbols and thousands separators; drop it if you prefer base R.
Tables in one call
Many public statistics pages publish HTML tables. html_table() converts one into a data frame directly, with the header row as column names.
rates <- base_req |>
req_url_path("/tables/population") |>
req_perform() |>
resp_body_html() |>
html_element("table#by-region") |>
html_table()
str(rates)
Numbers often arrive as text because of separators or footnote marks. Clean them after reading, and check the result with str() before analysis.
Looping through pages
Write a function for one page and loop over page numbers until a page comes back empty. Because the template already throttles and retries, the loop itself stays simple.
scrape_page <- function(n) {
r <- base_req |>
req_url_path("/regions/indicators") |>
req_url_query(year = 2024, page = n) |>
req_error(is_error = \(resp) resp_status(resp) >= 500) |>
req_perform()
if (resp_status(r) != 200) return(NULL)
items <- resp_body_html(r) |> html_elements("div.indicator")
if (length(items) == 0) return(NULL)
data.frame(page = n,
name = items |> html_element("h3") |> html_text2())
}
collected <- list()
for (n in 1:40) {
chunk <- scrape_page(n)
if (is.null(chunk)) break
collected[[n]] <- chunk
}
all_rows <- do.call(rbind, collected)
req_error() changes which statuses raise an R error. Here client errors such as 404 come back as ordinary responses, so the function can stop quietly at the end of the pages, while server errors (after the retries are used up) still raise. The upper bound of 40 pages protects against a site that never returns an empty page.
JSON endpoints are easier
If the page loads its data from a JSON API, call that API instead of parsing HTML. httr2 parses JSON into lists with resp_body_json(), and a do.call(rbind, ...) or dplyr::bind_rows() turns records into a data frame. Look for these calls in the browser's Network panel under Fetch/XHR, as described in hidden API scraping.
Pages that need JavaScript
rvest reads the HTML the server sends. When a page builds its content with JavaScript, that HTML may contain only an empty shell. Recent rvest versions add read_html_live(), which drives a headless Chrome through the chromote package and returns the rendered page; it needs Chrome installed and is much slower than plain requests, so use it only for pages that truly need it.
Handling a CAPTCHA from R
If a page answers with a challenge, for example a Turnstile widget in a form, the same httr2 tools talk to a CAPTCHA API. Create a task with a JSON body, then poll:
gs_call <- function(method, body) {
request(paste0("https://gatesolver.com/", method)) |>
req_body_json(c(list(clientKey = Sys.getenv("GATESOLVER_KEY")), body)) |>
req_perform() |>
resp_body_json()
}
job <- gs_call("createTask", list(task = list(
type = "AntiTurnstileTaskProxyLess", websiteURL = "https://stats.example.org/download",
websiteKey = "0x4AAAAAAA_r_placeholder")))
repeat {
Sys.sleep(3)
st <- gs_call("getTaskResult", list(taskId = job$taskId))
if (st$errorId != 0 || st$status == "failed") stop("task failed: ", st$errorCode)
if (st$status == "ready") break
}
turnstile_token <- st$solution$token
Then submit the form with req_body_form(), including `cf-turnstile-response` = turnstile_token and the form's other fields. Keep the API key in an environment variable (for example in .Renviron), never in a script you share. A task that is not solved within two minutes is marked failed and costs nothing, so the loop always ends.
Keep raw pages while you develop
Selectors rarely come out right the first time. Instead of fetching the same page again for every attempt, save the raw response once with writeLines(resp_body_string(resp), "cache/indicators-p1.html") and point read_html() at the file while you refine the parsing code. You avoid needless load on the site, your iterations run instantly, and the saved files double as test fixtures later. When the parsing works, switch back to live requests for the full run.
Good practice for research scraping
- Identify your scraper with a contact address in the user agent, as the template does.
- Keep throttling conservative; research jobs are rarely urgent.
- Cache raw responses to disk during development so you do not re-download while refining selectors.
- Record the date of collection alongside the data; public pages change.
Common questions
Should I use rvest read_html or httr2 to fetch pages?
read_html is fine for quick checks. httr2 adds retries, throttling, timeouts and error control, which unattended scripts need.
What is the difference between html_elements and html_element?
html_elements returns every match; html_element returns one match per input node, with a missing value where none exists, which keeps columns aligned.
How do I slow down an R scraper?
Add req_throttle to the base request with a rate such as 20 per 60 seconds; it applies across all requests in the session.
Can rvest scrape JavaScript rendered pages?
Plain rvest reads server HTML only. Recent versions offer read_html_live, which renders the page in headless Chrome through chromote.
How do I read an HTML table into a data frame?
Select the table with html_element and pass it to html_table, then clean numeric columns that arrive as text.
Keep reading
- Web scrapingWeb scraping means fetching pages and pulling structured data out of them, within the legal and ethical limits of the sites involved.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.
- Rate limitingCaps on requests per IP, key or session, the 429 response that enforces them, and the limit GateSolver applies to its own API.
- Solve Cloudflare Turnstile in PythonAn asyncio and aiohttp client for Turnstile tasks, with action and cData passed through and the token posted as cf-turnstile-response.