Blog Cover

How to count html tags in a web page by using web url

Muhammad  Ahmad

Muhammad Ahmad

June 24, 2021

18 

  • Create new rails app

  • Install following Gems

gem 'nokogiri'
gem 'open-uri'
  • Script
begin
  @doc = Nokogiri::HTML(URI.open(params[:page][:url]).read)
  @summary = @doc.xpath("//*").map(&:name).each_with_object({}) {|n, r| r[n] = (r[n] || 0) + 1 }
rescue Exception => e
  puts "Couldn't read \"#{ params[:page][:url] }\": #{ e }"
end
  • View
<% @summary.each do |tag, count| %>
  <div>
    <%= tag %>: <%= count %>
  </div>
<% end %>

Github Repo: rails-UrltoHtml Demo Link: rails-UrltoHtml

React, comment and follow on