Parsing HTML
suggest changeParsing and manipulating HTML is a common task in web scraping, data extraction, email processing, and template transformation. In Ruby, Nokogiri is the standard, high-performance HTML/XML parser. Modern Nokogiri includes full support for both the HTML5 standard (via the embedded Google Gumbo parser) and legacy HTML4.
1. Installing and Requiring Nokogiri
Install Nokogiri:
gem install nokogiri
In your Ruby script:
require 'nokogiri'
2. Parsing HTML Documents and Fragments
Full Document Parsing: HTML5 vs. HTML4
For modern web content, use Nokogiri::HTML5 (which strictly follows the WHATWG HTML5 specification for error handling and tree construction). For legacy or quirks-mode documents, use Nokogiri::HTML4:
raw_html = <<~HTML
<!DOCTYPE html>
<html>
<head><title>Product Catalog</title></head>
<body>
<div id="content">
<h1>Items</h1>
<ul class="items">
<li data-sku="A101">Laptop - $999</li>
<li data-sku="B202">Mouse - $29</li>
</ul>
</div>
</body>
</html>
HTML
# Parse as HTML5 document
doc = Nokogiri::HTML5(raw_html)
puts doc.title #=> "Product Catalog"
Parsing HTML Fragments
When parsing small snippets of HTML (e.g. from user comments, blog posts, or API fragments) without wrapping <html> or <body> tags:
snippet = '<p>Check out <a href="https://example.com">this link</a>!</p>'
fragment = Nokogiri::HTML5.fragment(snippet)
link = fragment.at_css('a')
puts link['href'] #=> "https://example.com"
puts link.text #=> "this link"
3. Querying the DOM Tree: CSS Selectors vs. XPath
Nokogiri provides two primary query methods:
.css('selector'): Evaluates standard CSS selectors. Returns aNokogiri::XML::NodeSet..xpath('expression'): Evaluates XPath 1.0 expressions.
# Querying with CSS
doc.css('ul.items > li').each do |item|
sku = item['data-sku']
text = item.text.strip
puts "SKU: #{sku} | Text: #{text}"
end
# Querying with XPath
laptops = doc.xpath("//li[contains(text(), 'Laptop')]")
puts laptops.first.text #=> "Laptop - $999"
.css vs .at_css
.css('selector')returns all matching elements (NodeSet)..at_css('selector')returns the first matching element (ornilif none match). Equivalent to.css(...).first.
4. Navigating and Traversing the DOM
Nokogiri nodes provide convenient relational traversal methods:
ul = doc.at_css('ul.items')
# Relational access
first_li = ul.first_element_child
second_li = first_li.next_element
puts first_li.text #=> "Laptop - $999"
puts second_li.text #=> "Mouse - $29"
# Parent and ancestor navigation
parent_div = first_li.parent.parent # climbs up <ul> to <div id="content">
puts parent_div['id'] #=> "content"
# Find closest matching ancestor
closest_div = first_li.ancestors('div').first
5. Modifying and Transforming HTML
Nokogiri allows you to modify attributes, insert new tags, and sanitize HTML trees in-place:
doc = Nokogiri::HTML5.fragment('<div class="article"><p>Draft text</p></div>')
# 1. Mutate attributes
div = doc.at_css('div')
div['class'] = 'article published'
div['data-status'] = 'ready'
# 2. Add new nodes
div.add_child('<span class="badge">New</span>')
# 3. Update inner text
p_tag = doc.at_css('p')
p_tag.content = "Final reviewed text."
# 4. Remove elements with unlink
badge = doc.at_css('.badge')
badge.unlink # Completely removes the node from DOM
# 5. Output transformed HTML
puts doc.to_html
# Output: <div class="article published" data-status="ready"><p>Final reviewed text.</p></div>
6. Sanitizing Untrusted HTML to Prevent XSS
When rendering user-generated HTML, never render raw strings. Use Nokogiri directly or via Loofah (the HTML sanitizer behind Rails) to scrub unsafe tags and scripts:
require 'loofah'
untrusted_user_input = <<~HTML
<p>Hello! <script>alert('Stealing cookies!');</script> Click <a href="javascript:attack()">here</a>.</p>
HTML
# Scrub dangerous scripts, iframes, and javascript: links
safe_html = Loofah.fragment(untrusted_user_input).scrub!(:prune).to_s
puts safe_html
# Output: <p>Hello! Click <a>here</a>.</p>
Best Practices
- Prefer
Nokogiri::HTML5overNokogiri::HTML: HTML5 mode provides standardized parsing conforming to modern browser engines. - Use
.at_cssWhen Expecting Single Elements: Avoid.css(...).firstto improve readability and stop searching once the first match is found. - Always Clean Up with
.unlink: When stripping ad trackers, script tags, or comments, use.unlinkto detach nodes cleanly from the memory tree.