Created
July 15, 2017 16:28
-
-
Save b1nary/91484f8ab0f6116861e0e829ad83d6c8 to your computer and use it in GitHub Desktop.
Basic but well working way to find favicons by domain in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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