Skip to content

Instantly share code, notes, and snippets.

@b1nary
Created July 15, 2017 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b1nary/91484f8ab0f6116861e0e829ad83d6c8 to your computer and use it in GitHub Desktop.
Save b1nary/91484f8ab0f6116861e0e829ad83d6c8 to your computer and use it in GitHub Desktop.
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