Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic but well working way to find favicons by domain in Ruby
class FaviconFinder
require 'open-uri'
attr_accessor :favicon_url
def initialize domain = "example.com"
@favicon_url = nil
["/favicon.ico", "/favicon.png"].each do |file|
url = "http://#{domain}#{file}"
uri = URI(url)
request = Net::HTTP.new uri.host
response= request.request_head uri.path
if response.code.to_i == 301
url = response.header['location']
uri = URI(url)
request = Net::HTTP.new uri.host
response= request.request_head uri.path
end
@favicon_url = url if response.code.to_i == 200
end
if @favicon_url.nil?
index = open("http://#{domain}")
data = Nokogiri::HTML(index.read)
@favicon_url = data.css('link[rel="shortcut icon"]').first
@favicon_url = data.css('link[rel="icon"]').first if @favicon_url.nil?
if !@favicon_url.nil? && !@favicon_url['href'].include?(index.base_uri.to_s)
@favicon_url = "#{index.base_uri.to_s}#{@favicon_url['href']}"
end
end
end
end
FaviconFinder.new("facebook.com").favicon_url
FaviconFinder.new("google.com").favicon_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.