html_element() and html_text() Basics
Extract text, attributes, and table data from scraped pages.
html_element() and html_text() Basics is a free R Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
read_html(): Loading a Page
read_html() is the entry point for rvest. Pass a URL or a raw HTML string. It returns an xml_document object representing the parsed DOM tree, ready for querying.
library(rvest)
# From a URL (requires internet connection)
# page <- read_html('https://books.toscrape.com')
# From a raw HTML string (great for testing)
page <- read_html('
<html><body>
<h1>Book Store</h1>
<p class="desc">Over 1000 books!</p>
</body></html>
')
class(page) # 'xml_document' 'xml_node'html_element() vs html_elements()
html_element() returns the first matching node (or NA if none found). html_elements() returns all matching nodes as a list. Use singular when you expect exactly one result, plural when scraping lists.
library(rvest)
page <- read_html('
<ul>
<li class="item">Apple</li>
<li class="item">Banana</li>
<li class="item">Cherry</li>
</ul>
')
# Singular: gets first match
first_item <- html_element(page, '.item')
html_text2(first_item) # 'Apple'
# Plural: gets all matches
all_items <- html_elements(page, '.item')
html_text2(all_items) # c('Apple', 'Banana', 'Cherry')
length(all_items) # 3html_text2() for Clean Text
html_text2() extracts text content from nodes, stripping HTML tags and collapsing whitespace cleanly. It handles <br> as newlines. The older html_text() is less smart about whitespace.
library(rvest)
page <- read_html('
<div class="product">
<h2> Laptop </h2>
<p>Price: <strong>$999</strong></p>
<p> Free shipping </p>
</div>
')
# html_text2 trims whitespace intelligently
title <- html_element(page, 'h2')
html_text2(title) # 'Laptop' (no extra spaces)
# From the whole div - collapses nested text
div <- html_element(page, '.product')
html_text2(div) # 'Laptop\nPrice: $999\nFree shipping'html_attr(): Extracting Attributes
html_attr(node, 'attr_name') extracts the value of an HTML attribute. This is essential for getting href from links, src from images, data-* attributes, and more.
library(rvest)
page <- read_html('
<div>
<a href="https://example.com" title="Example site">Visit</a>
<img src="/images/photo.jpg" alt="A photo">
<div data-price="29.99">Product</div>
</div>
')
# Extract href from link
link <- html_element(page, 'a')
html_attr(link, 'href') # 'https://example.com'
html_attr(link, 'title') # 'Example site'
# Extract src from image
img <- html_element(page, 'img')
html_attr(img, 'src') # '/images/photo.jpg'
# Extract data attributes
div <- html_element(page, 'div[data-price]')
html_attr(div, 'data-price') # '29.99'html_attrs(): All Attributes
html_attrs(node) returns a named character vector of ALL attributes on a node. Useful when you don't know attribute names in advance, or want to inspect what's available on an element.
library(rvest)
page <- read_html('
<a href="/page" class="nav-link" id="home" data-section="main">Home</a>
')
link <- html_element(page, 'a')
# Get all attributes at once
attrs <- html_attrs(link)
attrs
# href class id data-section
# '/page' 'nav-link' 'home' 'main'
# Access by name
attrs['href'] # '/page'
attrs['class'] # 'nav-link'
names(attrs) # all attribute nameshtml_children(): Child Nodes
html_children(node) returns the immediate child nodes of an element. Combined with html_name() to get tag names, this is useful for understanding page structure programmatically.
library(rvest)
page <- read_html('
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<span>|</span>
<a href="/contact">Contact</a>
</nav>
')
nav <- html_element(page, 'nav')
# Get all direct children
kids <- html_children(nav)
length(kids) # 4
# Get tag names of children
html_name(kids) # c('a', 'a', 'span', 'a')
# Filter to only anchor children
links <- kids[html_name(kids) == 'a']
html_text2(links) # c('Home', 'About', 'Contact')html_name(): Tag Names
html_name(node) returns the tag name of a node as a lowercase string (e.g., 'div', 'p', 'a'). Useful for filtering node lists by element type after retrieval.
library(rvest)
page <- read_html('
<article>
<h2>Title</h2>
<p>First paragraph.</p>
<img src="img.jpg">
<p>Second paragraph.</p>
</article>
')
article <- html_element(page, 'article')
all_children <- html_children(article)
# Check tag name of each child
html_name(all_children)
# c('h2', 'p', 'img', 'p')
# Get only paragraph children
paras <- all_children[html_name(all_children) == 'p']
html_text2(paras)
# c('First paragraph.', 'Second paragraph.')Chaining Selections
You can pass a node (not just the document) as the first argument to html_element(). This scopes the search to within that node — crucial for scraping repeated structures like product cards or table rows.
library(rvest)
page <- read_html('
<div class="card">
<h3>Laptop</h3>
<span class="price">$999</span>
</div>
<div class="card">
<h3>Phone</h3>
<span class="price">$499</span>
</div>
')
# Get all cards, then extract fields from each
cards <- html_elements(page, '.card')
names_list <- html_text2(html_elements(page, '.card h3'))
prices_list <- html_text2(html_elements(page, '.card .price'))
data.frame(name = names_list, price = prices_list)html_attr on a NodeSet
When called on a nodeset (result of html_elements()), html_attr() returns a vector of attribute values — one per node. Missing attributes return NA.
library(rvest)
page <- read_html('
<ul>
<li><a href="/page1">Page 1</a></li>
<li><a href="/page2">Page 2</a></li>
<li><span>No link</span></li>
<li><a href="/page3">Page 3</a></li>
</ul>
')
# Get all a elements
links <- html_elements(page, 'a')
# html_attr on a nodeset returns a vector
hrefs <- html_attr(links, 'href')
hrefs # c('/page1', '/page2', '/page3')
# Link text alongside hrefs
texts <- html_text2(links)
data.frame(text = texts, href = hrefs)Handling Missing Elements
html_element() returns an NA node (not NULL) when nothing matches. html_text2() on an NA node returns NA_character_. Always check for NA in your results when elements may be optional.
library(rvest)
page <- read_html('
<div class="product">
<h3>Widget</h3>
<!-- No price tag here -->
</div>
')
# Element exists
title <- html_element(page, 'h3')
html_text2(title) # 'Widget'
# Element does NOT exist -> NA node
price <- html_element(page, '.price')
html_text2(price) # NA
is.na(html_text2(price)) # TRUE
# Safe extraction with default
price_text <- html_text2(price)
if (is.na(price_text)) price_text <- 'N/A'
price_text # 'N/A'Putting It Together
Combine html_elements(), html_text2(), and html_attr() to scrape structured data into a data frame — the typical end goal of web scraping with rvest.
library(rvest)
page <- read_html('
<div class="book">
<a href="/book/1" class="title">R Programming</a>
<span class="author">Hadley Wickham</span>
<span class="rating" data-stars="5">*****</span>
</div>
<div class="book">
<a href="/book/2" class="title">Advanced R</a>
<span class="author">Hadley Wickham</span>
<span class="rating" data-stars="5">*****</span>
</div>
')
titles <- html_text2(html_elements(page, '.title'))
authors <- html_text2(html_elements(page, '.author'))
links <- html_attr(html_elements(page, 'a.title'), 'href')
ratings <- html_attr(html_elements(page, '.rating'), 'data-stars')
data.frame(title=titles, author=authors, link=links, stars=ratings)Quick Check
Test your knowledge of rvest's core functions for navigating HTML documents.
Recap: rvest Core Functions
Key takeaways: read_html() loads pages; html_element() gets the first match; html_elements() gets all matches. Extract text with html_text2(), attributes with html_attr(), child nodes with html_children(), and tag names with html_name(). Missing elements return NA nodes — always handle NA in production scrapers.
library(rvest)
# Core rvest workflow:
# 1. Load page
# page <- read_html(url)
# 2. Find elements
# node <- html_element(page, 'css-selector')
# nodes <- html_elements(page, 'css-selector')
# 3. Extract content
# html_text2(node) -> text content
# html_attr(node, 'href') -> attribute value
# html_attrs(node) -> all attributes
# html_name(node) -> tag name
# html_children(node) -> child nodes
# 4. Build data frame
# data.frame(title = html_text2(...), link = html_attr(...))
cat('rvest follows the tidy data philosophy')Frequently asked questions
Is the “html_element() and html_text() Basics” lesson free?
Yes — the full text of “html_element() and html_text() Basics” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “html_element() and html_text() Basics”?
Extract text, attributes, and table data from scraped pages. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “html_element() and html_text() Basics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- HTML Structure and CSS Selectors
- html_element() and html_text() Basics
- Scraping Tables and Links
- Handling Pagination and Multiple Pages