Web scraping
Web scraping with Ruby
Ruby reads almost like prose, which makes scrapers easy to maintain. This guide fetches pages with the standard library or HTTParty, parses them with Nokogiri, and uses Ruby's own retry keyword to handle the bad days.
Choosing the HTTP layer
Ruby gives you two comfortable options. Net::HTTP ships with Ruby, needs no gems, and can hold one connection open for many requests, which is efficient when you fetch many pages from one host. HTTParty is a popular gem that wraps HTTP in a friendlier interface: one line per request, automatic parsing of JSON, and easy defaults. Both are fine for scraping; the examples below show each so you can pick the one that fits your project.
For parsing, Nokogiri is the standard, and it works the same whichever HTTP layer you choose. It is built on libxml2, fast, and supports both CSS selectors and XPath.
# Gemfile
source "https://rubygems.org"
gem "nokogiri"
gem "httparty"
gem "csv"
The csv line is there because CSV moved from a default gem to a bundled gem in Ruby 3.4; on older Rubies it is harmless.
Many pages over one connection with Net::HTTP
Net::HTTP.start with a block opens a connection, yields it, and closes it when the block ends. Every request inside the block reuses the same TCP and TLS session, which is faster and lighter for the server than reconnecting per page.
require "net/http"
require "nokogiri"
HEADERS = {
"User-Agent" => "Mozilla/5.0 (X11; Linux x86_64) recipe-index/0.4",
"Accept-Language" => "en-IE,en;q=0.8"
}.freeze
def each_page(host, paths)
Net::HTTP.start(host, 443, use_ssl: true, open_timeout: 5, read_timeout: 20) do |conn|
paths.each do |path|
res = conn.request(Net::HTTP::Get.new(path, HEADERS))
yield path, res
sleep(rand(0.8..2.0))
end
end
end
Net::HTTP does not follow redirects or keep cookies for you. For a fixed list of pages on one host that is rarely a problem; when it is, HTTParty or a gem with a cookie jar saves work.
Parsing with Nokogiri
Recipe = Struct.new(:title, :minutes, :url, keyword_init: true)
def parse_recipes(html, base)
doc = Nokogiri::HTML(html)
doc.css("article.recipe").map do |card|
link = card.at_css("a.recipe-link")
Recipe.new(
title: card.at_css("h2")&.text&.strip,
minutes: card.at_xpath(".//span[@itemprop='totalTime']")&.text.to_s[/\d+/]&.to_i,
url: link && URI.join(base, link["href"]).to_s
)
end
end
css returns every match, at_css the first or nil. The safe navigation operator &. keeps one missing element from raising an exception for the whole page. Mixing CSS and XPath is fine in Nokogiri; here XPath reads an attribute based condition that is just as easy in CSS, but XPath shines when you need text matching or axes such as siblings.
Retrying with rescue and retry
Ruby's retry keyword re-runs a begin block from the top, which makes retry logic short and readable. Combined with a counter and a growing sleep, it handles transient failures neatly.
class TransientError < StandardError; end
def fetch_body(conn, path, tries: 4)
attempt = 0
begin
attempt += 1
res = conn.request(Net::HTTP::Get.new(path, HEADERS))
code = res.code.to_i
raise TransientError, "status #{code}" if code == 429 || code >= 500
code == 200 ? res.body : nil
rescue TransientError, Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNRESET => e
raise if attempt >= tries
warn "retry #{attempt} for #{path}: #{e.message}"
sleep(2**attempt + rand)
retry
end
end
The last error is re-raised once the budget is spent, so a permanently failing page surfaces instead of being silently skipped. A 404 or other client error returns nil right away. Wrapping only specific exceptions keeps programming errors, such as a typo in a method name, from being retried pointlessly.
The same job with HTTParty
HTTParty shines when you hit several hosts, follow redirects, or call JSON endpoints. A class with include HTTParty holds shared defaults.
require "httparty"
class RecipeSite
include HTTParty
base_uri "https://cook.example.org"
headers HEADERS
default_timeout 20
end
page = RecipeSite.get("/recipes", query: { page: 2, sort: "new" })
if page.code == 200
parse_recipes(page.body, "https://cook.example.org").each { |r| puts r.title }
else
warn "got #{page.code}"
end
HTTParty follows redirects by default and parses JSON responses into hashes when the content type says JSON, so page.parsed_response is often all you need for an API.
Writing results
require "csv"
CSV.open("recipes.csv", "w") do |csv|
csv << %w[title minutes url]
each_page("cook.example.org", (1..5).map { |n| "/recipes?page=#{n}" }) do |path, res|
next warn("skip #{path}: #{res.code}") unless res.is_a?(Net::HTTPSuccess)
parse_recipes(res.body, "https://cook.example.org").each do |r|
csv << [r.title, r.minutes, r.url]
end
end
end
Rows are written as each page is parsed, so a crash late in the run still leaves the earlier pages on disk. If you need to resume, record the last finished page number in a small state file and start the range from there on the next run.
A few pages at once with threads
Ruby threads are a good fit for scraping because the work is mostly waiting on the network, and the interpreter releases its lock during I/O. A small pool is enough: put paths on a Queue, start three or four threads, and let each thread open its own Net::HTTP connection and pull paths until the queue is empty. Do not share one connection object between threads, since Net::HTTP is not built for concurrent use. Collect results in a thread safe Queue as well, then write the CSV from the main thread once all workers have joined. Keep the per thread sleep in place: four threads that each pause one to two seconds still add up to a steady, modest rate for the site.
When a CAPTCHA shows up
Ruby handles CAPTCHA APIs with the same tools. To solve a challenge, post a task to the API with Net::HTTP.post (available since Ruby 2.4) and a JSON body, then poll with sleep 3 between checks. For a reCAPTCHA form, submit the token as g-recaptcha-response together with the form fields; for an AWS WAF page, send the returned value in a Cookie: aws-waf-token=... header on the next request. The reCAPTCHA v2 Ruby guide and the Turnstile Ruby guide include complete clients. Detect the challenge first with a quick Nokogiri check, for example doc.at_css("[data-sitekey]"), so normal pages never pay for it.
Good habits
- Sleep between requests; the random range in
each_pageavoids a mechanical rhythm. - Check
robots.txtand the site's terms before a large run. - Keep selectors in one place so a layout change means one edit.
- Save a few raw pages and test
parse_recipesagainst them with Minitest or RSpec.
Common questions
Should I use Net::HTTP or HTTParty for scraping?
Net::HTTP needs no gems and reuses one connection well for many pages on a host. HTTParty is shorter to write and follows redirects for you.
Does Net::HTTP follow redirects?
No. You must read the Location header and request it yourself, or use HTTParty, which follows redirects by default.
What is the difference between css and at_css in Nokogiri?
css returns all matching nodes, at_css returns the first match or nil.
Why add the csv gem to my Gemfile?
In Ruby 3.4 csv became a bundled gem, so listing it keeps require csv working under Bundler.
How does retry work in Ruby?
Inside a rescue clause, retry runs the begin block again from the top. Pair it with a counter so it stops after a few attempts.
Keep reading
- Solve reCAPTCHA v2 in RubyRuby standard library only: Net::HTTP and JSON fetch a reCAPTCHA v2 token, and selenium-webdriver places it in the form.
- Solve Cloudflare Turnstile in RubyA Ruby Turnstile flow on Faraday with JSON middleware, a Nokogiri form reader and a Net::HTTP fallback for scripts without gems.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.
- CSS selectorCSS selectors are the compact pattern language for picking elements by tag, class, attribute and position, and most scraping tools speak it.