Skip to content

Instantly share code, notes, and snippets.

@jamiew
Created July 23, 2009 18:04
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 jamiew/153324 to your computer and use it in GitHub Desktop.
Save jamiew/153324 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# quickly lookup # of google search results for a given term
# usage: ~/bin/searchresults.rb "internet memes"
# by Jamie Wilkinson <http://jamiedubs.com>
# Free Art & Technology Lab <http://fffff.at>
require 'rubygems'
require 'mechanize'
# see also: pagerank.rb
module SEO
class GoogleSearch
def initialize(*opts)
@agent ||= WWW::Mechanize.new
# @agent.user_agent = 'searchresults.rb'
# google turns robot user agents down :( we're friendly, I swear
@agent.user_agent_alias = "Mac Safari"
end
# find the total number of search results for an arbitrary query on Google
def search_result_count(query)
@agent.get("http://www.google.com/search?q=#{query}") { |page|
elem = (page/'b')[4]
raise CannotScrape, "Could not find any search results for an allegedly supported search query, '#{query}'" if elem.nil?
count = elem.content.gsub(',','').to_i
return count
}
end
end
end
# execute with joined ARGV if called directly
if __FILE__ == $0
if ARGV.empty? || ARGV.first.empty?
puts "need a query"
exit 1
end
query = ARGV.join(' ')
count = SEO::GoogleSearch.new.search_result_count(query)
puts "#{count} search resuls for #{query.inspect}"
exit 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment