How to Use Nokogiri Gem

09/19/2021

Contents

In this article, you will learn how to use nokogiri gem.

How to use nokogiri gem

Nokogiri is a popular Ruby gem used for parsing HTML and XML documents. Here are the steps to use Nokogiri in your Ruby project:

Install the Nokogiri gem:

gem install nokogiri

Require Nokogiri in your Ruby code:

require 'nokogiri'

Parse an HTML or XML document using Nokogiri’s parse method:

doc = Nokogiri::HTML("<html><body><h1>Hello World!</h1></body></html>")

Once you have parsed the document, you can use Nokogiri’s API to extract information from the document. For example, to extract the text content of the h1 tag in the example above, you can use the following code:

puts doc.at('h1').text

This will output Hello World!.

You can also use Nokogiri to search for specific elements in the document using CSS or XPath selectors. For example, to extract all the links in a web page, you can use the following code:

doc.css('a').each do |link|
  puts link['href']
end

This will print the URLs of all the links in the document.

You can also use Nokogiri to modify the document by adding, deleting or modifying elements. For example, to add a new element to the document, you can use the following code:

doc.at('body').add_child('<p>Some new content</p>')

This will add a new p element with the text Some new content to the body of the document.