OneBite.Dev - Coding blog in a bite size

Scraping google search result with Ruby (For free)

Learn how to scrape google search result with Ruby. Without any paid service!

Here is how you can scrape Google search result with Ruby for free, without using any paid service.

We’ll use the same techinique on web scraping with Ruby for beginner

Love to watch a video instead?

Basic setup

We’re using net/http to perform get request and Nokogiri to parse the results

Feel free to change the keyword as you want

require 'net/http'
require 'nokogiri'

keyword = "computer"
url = "https://www.google.com/search?q=" + keyword
response = Net::HTTP.get_response(URI(url))


if response.code != "200"
    puts "Error: #{response.code}"
    exit
end

doc = Nokogiri::HTML(response.body)
print(doc)

Parse only Google search results

Our aim for now is to get only the search results. scrape google search results with ruby

Read what other hidden Gems in Google SERP for SEO

Find pattern

To separate the search results with other element, we need to find the pattern. Search, what separate the search results with other content. Either through browser inspect or your print result.

For this case, since Google randomize all the classes name, and differentiate when we browser directly and scraping, we’ll take a look on print result we have.

google search result pattern

Int his example, I notice that:

Here’s my code to get the title and link from Google search result above

require 'net/http'
require 'nokogiri'

keyword = "vs code"
url = "https://www.google.com/search?q=" + keyword
response = Net::HTTP.get_response(URI(url))


if response.code != "200"
    puts "Error: #{response.code}"
    exit
end

doc = Nokogiri::HTML(response.body)

# egMi0 kCrYT

doc.css('div.egMi0.kCrYT').each do |item|
    title = item.css('h3').text
    link = item.css('.BNeawe').text

    puts title + " || " + link
end

Scrape google search results, the easy way

If you don’t want to do this manually, there are tools out there, that can help you with this.

Why scrape google search results?

People scrape website content for various reasons, including:

Market Research and SEO

Content Aggregation

Academic Research

← Web scraping with Ruby (f...
Faster ruby scraping prog... →
ruby scraping