Ruby Web Scraping With Nokogiri: Working Code on Ruby 4.0
Ruby web scraping from zero to CSV: Nokogiri selectors, a polite pagination crawler, and the JavaScript wall. Every number measured on Ruby 4.0.9.

On this page
Ask five people about Ruby web scraping and you get the same stack: Nokogiri for parsing, something for fetching, and hope. What the tutorials skip is how each piece fails. I ran the whole path today on Ruby 4.0.9 (the current stable) with nokogiri 1.19.5, released today, against quotes.toscrape.com, a sandbox built for this: 1.2 seconds to fetch the first page, 0.76 milliseconds to parse it, 16 seconds for 100 quotes across ten pages, and zero quotes on the JavaScript variant.
Three working programs follow, one measured failure per step, and the exact point where Ruby stops being enough.
What you need
- Ruby 4.0.x. Current stable is 4.0.9 (Oct 23, 2026). Ruby 3.4.12 runs this code identically; 3.3 is in security-only maintenance and 3.2 is EOL, so don’t start a new project there.
- Nokogiri, installed with
gem install nokogiri. Version 1.19.5 requires Ruby 3.2 or newer and ships a precompiled native gem for x86_64 Linux (3.9 MB). That install took 3.0 seconds on this machine with no compiler involved. If your lockfile pins 1.19.3 or older, upgrade regardless of this tutorial: rubygems.org flags those releases with security advisories. - The sandbox: quotes.toscrape.com: ten quotes per page, pagination, a login form, and a JavaScript variant at
/js/. It publishes no robots.txt (the URL itself returns 404, rechecked today) and exists to be scraped. On real sites, read robots.txt and the terms of service before you point code at them.
Step 1: Fetch with open-uri, no gems
Ruby’s standard library covers the fetch. open-uri is part of it, so the first version of a scraper needs zero gems.
# fetch.rb
require "open-uri"
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
html = URI.open("https://quotes.toscrape.com/").read
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000
puts "#{html.bytesize} bytes, #{ms.round(0)} ms, #{html.encoding}"
11064 bytes, 1218 ms, UTF-8
That 1,218 ms includes the TLS handshake; repeat runs land well under it. Encoding comes back UTF-8 and Nokogiri keeps it that way, so smart quotes survive intact.
First failure case: open-uri raises on any 4xx or 5xx. A missing page is an exception, not a status code.
# notfound.rb
require "open-uri"
begin
URI.open("https://quotes.toscrape.com/no-such-page/")
rescue OpenURI::HTTPError => e
puts "#{e.class}: #{e.message}"
puts e.io.read[0, 120]
end
OpenURI::HTTPError: 404 NOT FOUND
<!doctype html>
<html lang=en>
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the
Net::HTTP, the other stdlib option, behaves the opposite way: it hands you the response object and never raises on a status code. Both are fine. Pick one per project and learn its error model, because the failure you didn’t expect is the one that fills your database with nothing.
One more measured detail: open-uri sends User-Agent: Ruby by default. I confirmed it against httpbin.org/get — the literal string, no version, no contact. Some sites refuse requests with empty or generic UAs on principle. Set one that names your scraper honestly:
html = URI.open(url, "User-Agent" => "QuoteBot/1.0 (+mailto:[email protected])").read
Step 2: Select with Nokogiri, the Ruby web scraping workhorse
Nokogiri turns HTML into a document you can query with CSS selectors or XPath. Parsing is not where your time goes: on this 11 KB page it averaged 0.76 ms over 50 runs, and the gem compiles libxml2 2.13.9 into itself, so behavior doesn’t depend on the system’s parser.
# parse.rb
require "open-uri"
require "nokogiri"
html = URI.open("https://quotes.toscrape.com/").read
doc = Nokogiri::HTML(html)
doc.css("div.quote").first(2).each do |q|
puts({
text: q.at_css("span.text").text,
author: q.at_css("small.author").text,
tags: q.css("a.tag").map(&:text),
}.inspect)
end
puts "quotes on page: #{doc.css("div.quote").length}"
{text: "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”", author: "Albert Einstein", tags: ["change", "deep-thoughts", "thinking", "world"]}
{text: "“It is our choices, Harry, that show what we truly are, far more than our abilities.”", author: "J.K. Rowling", tags: ["abilities", "choices"]}
quotes on page: 10
css returns every match, at_css returns the first one. XPath works on the same document, and its one big trap is measurable. A child step in XPath is strict: //div[@class='quote']/small[@class='author'] returns zero authors here, because the sandbox nests the <small> inside a <span> and / demands a direct child. Swap the second slash for a descendant search and it finds all ten:
authors = doc.xpath("//div[@class='quote']//small[@class='author']")
puts "#{authors.length} authors, first: #{authors.first.text}" # => 10 authors, first: Albert Einstein
Reach for XPath when the filter isn’t a plain class match — //a[@class='tag'][starts-with(., 'life')] returns the three life-prefixed tags and has no CSS equivalent. The curly quotes arrive intact: the page ships them as literal UTF-8, and nothing in the fetch-parse path mangles them.
Now the failure mode that costs people weekends. A selector that matches nothing doesn’t raise. It returns nil, and the crash shows up one line later (backtrace trimmed below; the message is verbatim):
# nil.rb
require "nokogiri"
doc = Nokogiri::HTML("<html><body><p>hi</p></body></html>")
puts "at_css miss returns: #{doc.at_css("div.quote").inspect}"
doc.at_css("div.quote").text
at_css miss returns: nil
NoMethodError: undefined method 'text' for nil
The fix is safe navigation (q.at_css("span.text")&.text), which returns nil instead of crashing. But don’t swallow the nil: a redesign that mangles one div then produces a silent stream of empty records instead of an error. Count your records per run and treat a sudden drop as a bug alert.
Nokogiri also ships an HTML5 parser (Nokogiri::HTML5, parsing with Gumbo) alongside the default libxml2 HTML4 mode. For a sandbox this simple, both return the same tree. It matters on messy real-world markup, where HTML5 follows what a browser would actually build.
Step 3: Crawl the pagination, politely
The sandbox paginates through ten pages with a li.next link. The loop below follows it, collects 100 quotes, and writes a CSV with the standard library again.
# crawl.rb
require "open-uri"
require "nokogiri"
require "csv"
rows = []
url = "https://quotes.toscrape.com/"
UA = "QuoteBot/1.0 (+mailto:[email protected])"
loop do
doc = Nokogiri::HTML(URI.open(url, "User-Agent" => UA).read)
doc.css("div.quote").each do |q|
rows << [q.at_css("span.text")&.text, q.at_css("small.author")&.text,
q.css("a.tag").map(&:text).join("|"), url]
end
nxt = doc.at_css("li.next a")
break unless nxt
url = URI.join(url, nxt["href"]).to_s
sleep 0.5
end
CSV.open("quotes.csv", "w") { |csv| rows.each { |r| csv << r } }
puts "#{rows.length} quotes from #{rows.map { |r| r[3] }.uniq.length} pages"
100 quotes from 10 pages
The full run took 16.1 seconds wall clock on this connection, of which 4.5 seconds is deliberate sleep. URI.join resolves the sandbox’s root-relative href="/page/2/" against the current URL, which is the fiddly part people hand-roll wrong.
What the script doesn’t do is throttle itself beyond that sleep. Ruby ships no rate limiter, and this loop will happily hammer a fragile site at connection speed. The 0.5-second delay between requests is the whole politeness budget here; on a real target, check the site’s robots.txt for a Crawl-delay line and honor it. The mechanics live in our rate limiting glossary entry.
Step 4: The JavaScript wall
The sandbox has a variant that renders its quotes with JavaScript: same layout, same ten quotes, different delivery. The scraper above gets nothing:
# js.rb
require "open-uri"
require "nokogiri"
html = URI.open("https://quotes.toscrape.com/js/").read
doc = Nokogiri::HTML(html)
puts "quotes: #{doc.css("div.quote").length}, script tags: #{doc.css("script").length}"
quotes: 0, script tags: 2
Zero div.quote elements exist in the HTML Nokogiri sees. There is a cheat code on this particular page: the quotes sit in an inline var data = [...] JSON blob inside one of those script tags, so a regex could pull them out. That’s a sandbox luxury. Real JavaScript sites fetch their data from authenticated endpoints after the page loads, and no selector or regex gets you there from a static fetch.
The honest options, in order of weight: drive a real browser. Selenium with headless Chrome is the heavyweight classic; Capybara driving Ferrum is the lighter Ruby-native route. Either way you’re running Chrome, and page renders cost seconds instead of milliseconds. What that buys you and what it still misses is covered in JavaScript rendering and the dynamic websites guide.
A different shape of tool, for the record: Magpie (Go, AGPL-3.0-or-later or commercial license) starts from the same static fetch, then escalates to a real browser only when a page needs JavaScript, and keeps a cache of selectors per domain that re-synthesizes them when they break. It’s a standalone binary rather than a library, so it suits scrapes you don’t want to hand-maintain; for learning, the code above is the point.
What breaks outside the sandbox
Three things, none of them Ruby’s fault.
Selector rot is silent. Step 2’s nil behavior compounds across a crawl: a site redesign turns yesterday’s 100 rows into today’s 0 without a single exception. Log record counts every run. A number that moves is your early-warning system.
Real sites have opinions. The sandbox has no robots.txt and no rate limiter; production targets usually have both. A User-agent line banning your client, a Crawl-delay, a login wall: all normal. The login case has its own walkthrough in scraping sites with a login.
Some walls are below HTTP. Sites that fingerprint the TLS handshake reject your client no matter what headers you send. No Ruby gem fixes that; the realistic options are a proxy with client-hello impersonation or a real browser, and those are different budget lines. The Go sibling of this tutorial hits the same wall, and the Node.js one does too: every language’s static stack ends in the same place.
FAQ
Is Ruby good for web scraping?
For pages that serve HTML directly, yes: 0.76 ms parse times, UTF-8 handled, CSV in the stdlib, and Nokogiri has been Ruby’s default parser since 2008. It loses time on JavaScript-heavy targets, where any static stack needs a browser attached.
Nokogiri or Mechanize?
Mechanize wraps fetching and parsing in one object and keeps cookies across requests, which suits multi-step flows. Nokogiri alone is the better default today: Mechanize’s fetch layer is thin over the same primitives, and you’ll want explicit control of headers and errors anyway.
Can Nokogiri render JavaScript?
No. It parses markup, period. For JavaScript content you need a browser: Selenium or Capybara-with-Ferrum in Ruby, or a tool that does the rendering for you. The /js/ step above is the demo: 0 quotes, 2 script tags.
Does Nokogiri work on Windows?
Yes. rubygems.org lists precompiled gems for x64-mingw (Windows) alongside Linux and macOS builds, so gem install nokogiri needs no compiler there either. Same story on Apple silicon and musl-based Alpine images.
Is web scraping with Ruby legal?
Scraping public data is generally lawful; the fights happen over login-walled data, copyright, and terms-of-service violations, and courts have ruled both ways. Check robots.txt and the site’s terms, keep your request rate humane, and never scrape personal data you wouldn’t publish yourself. This isn’t legal advice.
Where this goes next
The sandbox has a login form at /login, which is the natural next exercise once the code above runs clean. Beyond it: Node.js reaches the same wall with Cheerio, and the Go version ends identically — the language changes, the JavaScript wall doesn’t. Learn the pattern here, where a missed selector costs you ten minutes, not a production incident.


