Web scraping
suggest changeWeb scraping in Ruby involves fetching HTML content over HTTP and parsing its document structure to extract targeted data. The standard, industry-wide library for parsing and querying HTML/XML in Ruby is Nokogiri.
Scraping with Nokogiri and OpenURI
Nokogiri wraps the fast C libraries libxml2 and libxslt, providing support for both CSS selectors and XPath expressions.
Install Nokogiri:
gem install nokogiri
Basic Scraping Example
Combine Ruby's standard library open-uri module with Nokogiri::HTML:
require 'nokogiri'
require 'open-uri'
url = 'https://news.ycombinator.com/'
# Set a custom User-Agent header when opening the URL.
# .read returns a String tagged with the charset from the HTTP header;
# passing the IO itself makes Nokogiri guess (often wrongly) the encoding.
html = URI.open(url, 'User-Agent' => 'RubyScraper/1.0').read
doc = Nokogiri::HTML(html)
# Extract story titles and their links using CSS selectors
doc.css('.titleline > a').each_with_index do |link, index|
title = link.text.strip
href = link['href']
puts "#{index + 1}. #{title}"
puts " URL: #{href}"
end
CSS Selectors vs. XPath
Nokogiri allows querying using CSS selectors (.css) or XPath (.xpath):
html_content = <<~HTML
<div class="product-list">
<div class="product" data-id="101">
<h2 class="name">Wireless Headphones</h2>
<span class="price">$79.99</span>
<a href="/products/101">View Details</a>
</div>
<div class="product" data-id="102">
<h2 class="name">Mechanical Keyboard</h2>
<span class="price">$129.99</span>
<a href="/products/102">View Details</a>
</div>
</div>
HTML
doc = Nokogiri::HTML(html_content)
# Using CSS selectors
doc.css('.product').each do |item|
id = item['data-id']
name = item.at_css('.name').text
price = item.at_css('.price').text
link = item.at_css('a')['href']
puts "Item ##{id}: #{name} - #{price} (#{link})"
end
# Using XPath to find products over $100
expensive = doc.xpath("//div[@class='product'][contains(span, '$129')]//h2")
puts "Expensive item: #{expensive.text}"
.css('selector')returns aNodeSet(an array-like collection of elements)..at_css('selector')returns only the first matching node (equivalent to.css('selector').first).['attr_name']retrieves an HTML attribute value.
Handling Forms and Sessions with Mechanize
For sites requiring login forms, session cookies, and multi-step navigation, the mechanize gem provides automated browser simulation:
require 'mechanize'
agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'
# Fetch login page
page = agent.get('https://example.com/login')
# Fill out and submit login form
form = page.form_with(id: 'login-form')
form.username = 'my_username'
form.password = 'my_password'
dashboard = agent.submit(form)
# Scrape protected content
puts "Dashboard Title: #{dashboard.title}"
Scraping JavaScript-Rendered Pages
If a web page renders its content dynamically with client-side JavaScript (e.g. React, Angular, or Vue), Nokogiri alone only sees the raw initial HTML shell. Use Ferrum (a pure Ruby driver for headless Chrome using the Chrome DevTools Protocol):
require 'ferrum'
browser = Ferrum::Browser.new(headless: true)
browser.go_to('https://spa-example.com')
# Wait for dynamic elements to appear
browser.network.wait_for_idle
# Extract dynamically rendered content
titles = browser.css('.dynamic-card h3').map(&:text)
titles.each { |t| puts t }
browser.quit
Best Practices and Etiquette
- Identify Your Bot: Supply a descriptive
User-Agentheader containing contact information. - Rate Limiting: Insert delays (
sleep(1.0)) between requests so target servers are not overwhelmed. - Error Handling: Rescue network exceptions (
OpenURI::HTTPError,SocketError,Net::OpenTimeout) to ensure your scraper resumes gracefully after intermittent failures.