Parsing HTML – like the pros
Ruby is often used to read websites (scraping). The most famous tool for that is Nokogiri – almost every Ruby program that reads HTML or XML uses it:
require "nokogiri"
doc = Nokogiri::HTML5(html)
doc.css("a").each { |link| puts link.text }On your machine Nokogiri is largely C: it ships the C libraries libxml2 and gumbo. In this browser Ruby runs as WebAssembly, where only pure-Ruby gems can be installed at runtime. So here you get nokogiri-pure: the same Nokogiri with its C parts translated to Ruby. It is slower, but gives the same results – and gems that need Nokogiri (loofah, sanitize, premailer, rubyXL …) run here too.
install_gem "nokogiri"The idea: first parse (text becomes a tree), then search with CSS selectors. Nokogiri::HTML5 reads HTML the way a modern browser does:
require "nokogiri"
html = "<html><body>
<h1>Menu</h1>
<ul>
<li><a href='/bacon'>Bacon</a></li>
<li><a href='/egg'>Egg</a></li>
<li><a href='/coffee'>Coffee</a></li>
</ul>
</body></html>"
doc = Nokogiri::HTML5(html)
doc.css("li").lengthdoc.css("li") finds all <li> elements – just like in a stylesheet. Every match is a node: text gives its text, and you read an attribute like a hash, with link["href"]:
doc.css("a").map { |link| link.text }css finds every match, at_css only the first one – handy when an element exists only once anyway. Besides CSS, Nokogiri also understands XPath, a query language of its own for such trees: //a[@href='/egg'] means “an a anywhere whose href equals /egg”:
puts doc.at_css("h1").text
doc.xpath("//a[@href='/egg']").textNokogiri can also change the tree and write it out as HTML again – here every link should open in a new tab:
doc.css("a").each { |link| link["target"] = "_blank" }
puts doc.at_css("ul").to_htmlAnd the other way round, a builder makes new HTML from Ruby code: every method call in the block becomes an element, a block below it becomes its content:
page = Nokogiri::HTML5::Builder.new do |b|
b.ul do
%w[Bacon Egg Coffee].each { |dish| b.li dish }
end
end
puts page.to_htmlmap to build an array links of all href values. You reach an attribute via link["href"]. Expected result: ["/bacon", "/egg", "/coffee"]. (Run the cells above first so doc exists.)# links = doc.css("a").map { |link| ... }