Question

I want to use ruby to check if a link died. Can you tell me a tool in ruby to check link died in ruby ? Can i use selenium or nokogiri? Thanks for your helping!

Was it helpful?

Solution

It should be enough to make request with Net::HTTP and check if status code is 404.

For example:

require 'net/http'
uri = URI('link_to_check')
response = Net::HTTP.get_response(uri)
if response.code == '404'
  # do something
end

OTHER TIPS

Here's something that I use. It does a HEAD instead of GET request and will follow redirects properly. It also uses the generic Net::HTTPSuccess to check if a request was successful.

require 'net/http'

def alive?(link, limit=10)
  return false if limit <= 0

  link = "http://#{link}" unless link =~ %r{^https?://}i
  uri = URI.parse(link)

  http = Net::HTTP.new(uri.host, uri.port)
  req = Net::HTTP::Head.new(uri.request_uri)
  res = http.request(req)

  case res
    when Net::HTTPSuccess then true
    when Net::HTTPRedirection then alive?(res['location'], limit-1)
    else false
  end
rescue SocketError
  false # unknown hostname
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top