Skip to content

Instantly share code, notes, and snippets.

@gtrak
Created September 9, 2013 15:34
Show Gist options
  • Save gtrak/6497276 to your computer and use it in GitHub Desktop.
Save gtrak/6497276 to your computer and use it in GitHub Desktop.
require 'mechanize'
def google_search(query_text)
agent=Mechanize.new
goog = agent.get "http://www.google.com"
search = goog.form_with(:action => "/search")
search.field_with(:name => 'q').value = query_text
results = search.submit
return results
end
require 'tempfile'
def with_temp_string(s)
file = Tempfile.new("arbitrary_prefix")
file.write(s)
file.close
yield file.path
sleep 5
file.unlink
end
require 'launchy'
ENV['BROWSER'] = 'google-chrome'
def browse_s(s)
with_temp_string(s) {|path| Launchy::Application::Browser.new.open(path)}
end
def browse_page(mechanize_page)
browse_s mechanize_page.body
end
def unwrap_link(l)
u = URI.parse(l)
p = CGI.parse(u.query)
return p['q'].first
end
def links(search_results)
return search_results.search("#ires ol .g .r a")
.map {|x| x['href']}
.keep_if {|x| URI.parse(x).path == "/url"}
.map {|x| unwrap_link x}
end
def im_feeling_lucky(search)
links = links(google_search(search))
Launchy.open(links.first)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment