Ruby HTML Parsing Gems Like Cheerio for Node.js
Short answer
Is there a Ruby gem for HTML parsing like Cheerio in Node.js?
Yes: Nokogiri. Like Cheerio, it parses HTML into a document you query with CSS selectors through css and at_css, and it also supports XPath. Oga is a pure-Ruby alternative without native extensions. Neither runs JavaScript, so fetch rendered HTML from an API such as AlterLab when a page builds its content client-side.
Step by step
- 1
Install Nokogiri
Add `gem 'nokogiri'` to your Gemfile and run bundle install.
- 2
Parse the HTML
Call Nokogiri::HTML(html) on the page body you downloaded.
- 3
Query with CSS selectors
Use doc.css('h2.title') for many elements or doc.at_css('h1') for the first match, just as you would with Cheerio's $().
Example
require "net/http"
require "nokogiri"
html = Net::HTTP.get(URI("https://example.com/articles"))
doc = Nokogiri::HTML(html)
doc.css("h2.title").each do |node|
puts node.text.strip
endFrequently Asked Questions
Nokogiri or Oga?
Nokogiri is faster and far more widely used. Choose Oga only when you cannot install native extensions in your environment.
How do I get JavaScript-rendered content in Ruby?
Fetch the rendered HTML from a rendering API, or drive a browser with Ferrum, then pass the HTML to Nokogiri.
Read the full guide
Ruby web scraping guideTry it with AlterLab
Send a URL, get the page back as HTML, markdown or JSON. Rendering, proxy rotation and retries are handled for you.
Your first scrape.
Sixty seconds.
Up to 5,000 free requests — about 5,000 Light, 500 Protected or 250 Dynamic requests. No credit card.
Just a POST request.
No credit card required · Up to 5,000 free requests (about 5,000 Light, 500 Protected or 250 Dynamic requests) · Balance never expires